<?php
// File: login.php (Diperbarui untuk role 'tim')
session_start();

// Ganti path ini jika berbeda
require 'config/database.php'; 

// --- MODIFIKASI DIMULAI DI SINI ---

$nama_sekolah_tampil = 'Nama Sekolah Default'; // Nilai default
$logo_file = null;

try {
    // Ambil data pengaturan sekolah
    $stmt_pengaturan = $pdo->prepare("SELECT nama_sekolah, logo FROM pengaturan WHERE id = 1 LIMIT 1");
    $stmt_pengaturan->execute();
    $pengaturan = $stmt_pengaturan->fetch(PDO::FETCH_ASSOC);

    if ($pengaturan) {
        $nama_sekolah_tampil = htmlspecialchars($pengaturan['nama_sekolah']);
        $logo_file = $pengaturan['logo']; // Hanya nama file, path akan ditambahkan di HTML
    }
} catch (PDOException $e) {
    // Jika ada masalah dengan koneksi/query pengaturan, gunakan nilai default dan catat error jika perlu
    error_log("Gagal mengambil data pengaturan: " . $e->getMessage());
}

// --- MODIFIKASI BERAKHIR DI SINI ---


// Cek jika user sudah login, redirect ke dashboard yang sesuai
if (isset($_SESSION['user_id']) && isset($_SESSION['role'])) {
    $role = $_SESSION['role'];
    
    // LOGIKA REDIRECTION BARU UNTUK ROLE 'tim'
    if ($role === 'admin' || $role === 'tim') {
        header("Location: admin/dashboard.php");
    } elseif ($role === 'penilai' || $role === 'guru' || $role === 'kepsek') {
        header("Location: $role/dashboard.php");
    } else {
        // Fallback jika role tidak dikenali
        header("Location: logout.php"); 
    }
    exit();
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error = 'Username dan password tidak boleh kosong!';
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id, username, password, nama_lengkap, role FROM users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                // Login berhasil, simpan data sesi
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
                $_SESSION['role'] = $user['role'];
                
                // Arahkan berdasarkan peran
                $role = $user['role'];
                
                // LOGIKA REDIRECTION BARU DI SINI
                if ($role === 'admin' || $role === 'tim') {
                    header("Location: admin/dashboard.php");
                } elseif ($role === 'penilai' || $role === 'guru' || $role === 'kepsek') {
                    header("Location: $role/dashboard.php");
                } else {
                    // Fallback
                    header("Location: logout.php");
                }
                exit();
            } else {
                $error = 'Username atau password salah!';
            }
        } catch (PDOException $e) {
            $error = "Terjadi masalah dengan koneksi database.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - OnPKKM</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            --primary: #2d5f3f;
            --secondary: #5a9f7f;
            --accent: #f8b739;
            --dark: #1a3a2a;
        }
        body {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .login-container { max-width: 450px; width: 100%; margin: 0 auto; }
        .login-card { background: white; border-radius: 20px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); }
        .login-header { 
            background: linear-gradient(135deg, var(--primary), var(--secondary)); 
            padding: 2.5rem 2rem; 
            text-align: center; 
            color: white; 
            /* Tambahan untuk menyesuaikan dengan index.php */
            border-top-left-radius: 20px;
            border-top-right-radius: 20px;
        }
        .login-header .logo-circle {
            width: 80px;
            height: 80px;
            background: white;
            border-radius: 50%;
            margin: 0 auto 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
            position: relative;
            z-index: 1;
            overflow: hidden;
        }
        /* Menggunakan font-awesome untuk ikon default */
        .login-header .logo-circle i {
            font-size: 2.5rem;
            color: var(--primary); /* Warna ikon */
        }
        
        .login-header .logo-circle img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
        }

        .login-header h3 { font-size: 1.8rem; font-weight: 700; margin: 0; }
        .login-header p { font-size: 1rem; margin: 0; }

        .login-body { padding: 2.5rem 2rem; }
        .btn-login { 
            background: linear-gradient(135deg, var(--primary), var(--secondary)); 
            border: none; 
            border-radius: 10px; 
            padding: 0.9rem; 
            font-weight: 600; 
            color: white; 
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(45, 95, 63, 0.4);
        }
        .btn-login:active {
             transform: translateY(0);
        }
        
        /* Style untuk input dan label agar mirip dengan login admin */
        .form-label { font-weight: 600; color: #374151; margin-bottom: 8px; font-size: 1rem; }
        .form-control { border-radius: 10px; padding: 0.8rem 1rem; }
        .form-control:focus { border-color: var(--primary); box-shadow: 0 0 0 0.25rem rgba(45, 95, 63, 0.25); }

        /* Style alert */
        .alert { border-radius: 10px; }

        /* Style untuk loading */
        .btn-login.loading {
            pointer-events: none;
            opacity: 0.7;
        }

        .btn-login.loading::after {
            content: '';
            position: absolute;
            width: 20px;
            height: 20px;
            top: 50%;
            left: 50%;
            margin-left: -10px;
            margin-top: -10px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* Hilangkan elemen yang tidak ada di login.php */
        /* .back-home tidak ada di index.php (login utama) */
    </style>
</head>
<body>
    <div class="container">
        <div class="login-container">
            <div class="login-card">
                <div class="login-header">
                    <div class="logo-circle">
                        <?php if ($logo_file): ?>
                            <img src="assets/img/logo/<?= htmlspecialchars($logo_file) ?>" alt="Logo Sekolah">
                        <?php else: ?>
                            <i class="fas fa-school"></i> 
                        <?php endif; ?>
                    </div>
                    <h3 class="mb-0">Aplikasi PKKM Online</h3>
                    <p class="mb-0 mt-2"><b><?= $nama_sekolah_tampil ?></b></p>
                </div>

                <div class="login-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <?= htmlspecialchars($error) ?>
                        </div>
                    <?php endif; ?>

                    <form action="index.php" method="post" id="loginForm">
                        <div class="mb-4">
                            <label for="username" class="form-label">Username</label>
                            <input type="text" class="form-control" id="username" name="username" placeholder="Masukkan username" required autocomplete="username" autofocus>
                        </div>

                        <div class="mb-4">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" class="form-control" id="password" name="password" placeholder="Masukkan password" required autocomplete="current-password">
                            </div>

                        <button type="submit" class="btn btn-login w-100" id="loginBtn">
                            <i class="fas fa-sign-in-alt me-2"></i>
                            Login
                        </button>
                    </form>
                </div>
                
                <div class="text-center p-3 text-muted" style="font-size: 0.85rem; border-top: 1px solid #eee;">
                    © 2025 OnPKKM. All rights reserved.
                </div>
            </div>
            
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Fungsi togglePassword dihapus karena elemen input toggle dihilangkan
        
        // Add loading animation on submit
        document.getElementById('loginForm').addEventListener('submit', function() {
            const btn = document.getElementById('loginBtn');
            btn.classList.add('loading');
            btn.innerHTML = 'Memproses...';
        });

        // Auto-focus on username field (tetap dipertahankan)
        document.getElementById('username').focus();

        // Add enter key support (tetap dipertahankan)
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('loginForm').submit();
            }
        });
    </script>
</body>
</html>