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

$user = mysqli_real_escape_string($conn, $_POST['username']);
$pass = md5($_POST['password']);
$selected_role = isset($_POST['selected_role']) ? $_POST['selected_role'] : 'siswa';

// Debug log
error_log("Login attempt - Username: $user, Role selected: $selected_role");

// 1. CEK DI TABEL USERS (INI YANG UTAMA)
$q = mysqli_query($conn, "SELECT * FROM users WHERE username='$user' AND password='$pass' LIMIT 1");

if (mysqli_num_rows($q) > 0) {
    $data = mysqli_fetch_assoc($q);
    
    // Validasi role
    if ($data['role'] === $selected_role || $selected_role === 'all') {
        $_SESSION['username'] = $user;
        $_SESSION['role'] = $data['role'];
        $_SESSION['nama'] = $data['nama'] ?? '';
        $_SESSION['user_id'] = $data['id'];

        // Redirect berdasarkan role
        switch ($data['role']) {
            case 'admin':
                header("Location: dashboard.php");
                exit;
                
            case 'guru':
                $qGuru = mysqli_query($conn, "SELECT * FROM guru WHERE nip='$user' LIMIT 1");
                if ($rowGuru = mysqli_fetch_assoc($qGuru)) {
                    $_SESSION['guru_id'] = $rowGuru['id'];
                    $_SESSION['nama_guru'] = $rowGuru['nama'];
                    $_SESSION['mapel'] = $rowGuru['mapel'];
                    $_SESSION['nama_lengkap'] = $rowGuru['nama'];
                }
                header("Location: dashboard_guru_piket.php");
                exit;
                
            case 'wali_kelas':
                $qWali = mysqli_query($conn, "SELECT * FROM wali_kelas WHERE nip_wali='$user' LIMIT 1");
                if ($rowWali = mysqli_fetch_assoc($qWali)) {
                    $_SESSION['wali_id'] = $rowWali['id'];
                    $_SESSION['kelas_diampu'] = $rowWali['kelas'];
                    $_SESSION['nama_wali'] = $rowWali['nama_wali'];
                    $_SESSION['nip_wali'] = $rowWali['nip_wali'];
                    $_SESSION['nama_lengkap'] = $rowWali['nama_wali'];
                }
                header("Location: dashboard_wali_kelas.php");
                exit;
                
            case 'siswa':
                $qSiswa = mysqli_query($conn, "SELECT * FROM siswa WHERE nisn='$user' LIMIT 1");
                if ($rowSiswa = mysqli_fetch_assoc($qSiswa)) {
                    $_SESSION['siswa_id'] = $rowSiswa['id'];
                    $_SESSION['nama_siswa'] = $rowSiswa['nama'];
                    $_SESSION['kelas_siswa'] = $rowSiswa['kelas'];
                    $_SESSION['nis'] = $rowSiswa['nis'];
                    $_SESSION['nisn'] = $rowSiswa['nisn'];
                    $_SESSION['nama_lengkap'] = 'Wali dari ' . $rowSiswa['nama'];
                }
                header("Location: dashboard_siswa.php");
                exit;
        }
    } else {
        header("Location: index.php?error=role");
        exit;
    }
}

// ============================================================
// 2. FALLBACK: KHUSUS UNTUK LOGIN PERTAMA KALI (SEEDING DATA)
//    Setelah user terdaftar di tabel users, fallback ini TIDAK AKAN DIPAKE
// ============================================================

// Cek sebagai Admin - HANYA untuk seeding pertama kali
if ($selected_role === 'admin' && $user === 'admin' && $_POST['password'] === 'admin123') {
    // Cek apakah admin SUDAH ADA di tabel users
    $cekAdmin = mysqli_query($conn, "SELECT * FROM users WHERE username='admin' AND role='admin'");
    
    if (mysqli_num_rows($cekAdmin) == 0) {
        // Admin belum ada, buat baru
        mysqli_query($conn, "INSERT INTO users (username, password, nama, role) 
                           VALUES ('admin', MD5('admin123'), 'Administrator', 'admin')");
        $_SESSION['user_id'] = mysqli_insert_id($conn);
        $_SESSION['username'] = 'admin';
        $_SESSION['role'] = 'admin';
        $_SESSION['nama_lengkap'] = 'Administrator';
        
        header("Location: dashboard.php");
        exit;
    } else {
        // Admin sudah ada, tapi user mencoba login dengan password default
        // Ambil data admin yang benar dari database
        $ambilAdmin = mysqli_query($conn, "SELECT * FROM users WHERE username='admin' AND role='admin' LIMIT 1");
        $dataAdmin = mysqli_fetch_assoc($ambilAdmin);
        
        // Cek password dari database
        if ($dataAdmin['password'] === md5('admin123')) {
            // Password masih default, boleh login
            $_SESSION['user_id'] = $dataAdmin['id'];
            $_SESSION['username'] = 'admin';
            $_SESSION['role'] = 'admin';
            $_SESSION['nama_lengkap'] = 'Administrator';
            header("Location: dashboard.php");
            exit;
        } else {
            // Password sudah diubah, tapi user mencoba login dengan password default
            // TOLAK LOGIN!
            header("Location: index.php?error=invalid");
            exit;
        }
    }
}

// Cek sebagai Guru Piket - FALLBACK (hanya jika belum ada di users)
if ($selected_role === 'guru') {
    $qGuru = mysqli_query($conn, "SELECT * FROM guru WHERE nip='$user' LIMIT 1");
    if (mysqli_num_rows($qGuru) > 0) {
        $guru = mysqli_fetch_assoc($qGuru);
        
        // Cek apakah sudah ada di tabel users
        $cekUser = mysqli_query($conn, "SELECT * FROM users WHERE username='$user' AND role='guru'");
        
        if (mysqli_num_rows($cekUser) == 0) {
            // Belum ada, coba buat baru dengan password default (NIP)
            if ($_POST['password'] === $user) {
                $hashed_password = md5($user);
                mysqli_query($conn, "INSERT INTO users (username, password, nama, role) 
                                   VALUES ('$user', '$hashed_password', '{$guru['nama']}', 'guru')");
                $_SESSION['user_id'] = mysqli_insert_id($conn);
                $_SESSION['username'] = $user;
                $_SESSION['role'] = 'guru';
                $_SESSION['guru_id'] = $guru['id'];
                $_SESSION['nama_guru'] = $guru['nama'];
                $_SESSION['mapel'] = $guru['mapel'];
                $_SESSION['nama_lengkap'] = $guru['nama'];
                header("Location: dashboard_guru_piket.php");
                exit;
            }
        } else {
            // Sudah ada di users, cek password dari tabel users
            $userData = mysqli_fetch_assoc($cekUser);
            if ($userData['password'] === $pass) {
                $_SESSION['user_id'] = $userData['id'];
                $_SESSION['username'] = $user;
                $_SESSION['role'] = 'guru';
                $_SESSION['guru_id'] = $guru['id'];
                $_SESSION['nama_guru'] = $guru['nama'];
                $_SESSION['mapel'] = $guru['mapel'];
                $_SESSION['nama_lengkap'] = $guru['nama'];
                header("Location: dashboard_guru_piket.php");
                exit;
            }
        }
    }
}

// Cek sebagai Wali Kelas - FALLBACK (hanya jika belum ada di users)
if ($selected_role === 'wali_kelas') {
    $qWali = mysqli_query($conn, "SELECT * FROM wali_kelas WHERE nip_wali='$user' LIMIT 1");
    if (mysqli_num_rows($qWali) > 0) {
        $wali = mysqli_fetch_assoc($qWali);
        
        $cekUser = mysqli_query($conn, "SELECT * FROM users WHERE username='$user' AND role='wali_kelas'");
        
        if (mysqli_num_rows($cekUser) == 0) {
            if ($_POST['password'] === $user) {
                $hashed_password = md5($user);
                mysqli_query($conn, "INSERT INTO users (username, password, nama, role) 
                                   VALUES ('$user', '$hashed_password', '{$wali['nama_wali']}', 'wali_kelas')");
                $_SESSION['user_id'] = mysqli_insert_id($conn);
                $_SESSION['username'] = $user;
                $_SESSION['role'] = 'wali_kelas';
                $_SESSION['wali_id'] = $wali['id'];
                $_SESSION['kelas_diampu'] = $wali['kelas'];
                $_SESSION['nama_wali'] = $wali['nama_wali'];
                $_SESSION['nip_wali'] = $wali['nip_wali'];
                $_SESSION['nama_lengkap'] = $wali['nama_wali'];
                header("Location: dashboard_wali_kelas.php");
                exit;
            }
        } else {
            $userData = mysqli_fetch_assoc($cekUser);
            if ($userData['password'] === $pass) {
                $_SESSION['user_id'] = $userData['id'];
                $_SESSION['username'] = $user;
                $_SESSION['role'] = 'wali_kelas';
                $_SESSION['wali_id'] = $wali['id'];
                $_SESSION['kelas_diampu'] = $wali['kelas'];
                $_SESSION['nama_wali'] = $wali['nama_wali'];
                $_SESSION['nip_wali'] = $wali['nip_wali'];
                $_SESSION['nama_lengkap'] = $wali['nama_wali'];
                header("Location: dashboard_wali_kelas.php");
                exit;
            }
        }
    }
}

// Cek sebagai Siswa - FALLBACK (hanya jika belum ada di users)
if ($selected_role === 'siswa') {
    $qSiswa = mysqli_query($conn, "SELECT * FROM siswa WHERE nisn='$user' LIMIT 1");
    if (mysqli_num_rows($qSiswa) > 0) {
        $siswa = mysqli_fetch_assoc($qSiswa);
        
        $cekUser = mysqli_query($conn, "SELECT * FROM users WHERE username='$user' AND role='siswa'");
        
        if (mysqli_num_rows($cekUser) == 0) {
            if ($_POST['password'] === $user) {
                $hashed_password = md5($user);
                mysqli_query($conn, "INSERT INTO users (username, password, nama, role) 
                                   VALUES ('$user', '$hashed_password', 'Wali dari {$siswa['nama']}', 'siswa')");
                $_SESSION['user_id'] = mysqli_insert_id($conn);
                $_SESSION['username'] = $user;
                $_SESSION['role'] = 'siswa';
                $_SESSION['siswa_id'] = $siswa['id'];
                $_SESSION['nama_siswa'] = $siswa['nama'];
                $_SESSION['kelas_siswa'] = $siswa['kelas'];
                $_SESSION['nis'] = $siswa['nis'];
                $_SESSION['nisn'] = $siswa['nisn'];
                $_SESSION['nama_lengkap'] = 'Wali dari ' . $siswa['nama'];
                header("Location: dashboard_siswa.php");
                exit;
            }
        } else {
            $userData = mysqli_fetch_assoc($cekUser);
            if ($userData['password'] === $pass) {
                $_SESSION['user_id'] = $userData['id'];
                $_SESSION['username'] = $user;
                $_SESSION['role'] = 'siswa';
                $_SESSION['siswa_id'] = $siswa['id'];
                $_SESSION['nama_siswa'] = $siswa['nama'];
                $_SESSION['kelas_siswa'] = $siswa['kelas'];
                $_SESSION['nis'] = $siswa['nis'];
                $_SESSION['nisn'] = $siswa['nisn'];
                $_SESSION['nama_lengkap'] = 'Wali dari ' . $siswa['nama'];
                header("Location: dashboard_siswa.php");
                exit;
            }
        }
    }
}

// Login gagal
header("Location: index.php?error=invalid");
exit;
?>