<?php
session_start();
require_once 'koneksi.php';

if (isset($_POST['login'])) {
    $username = mysqli_real_escape_string($koneksi, $_POST['username']);
    $password = $_POST['password'];

    // 1. CEK KE TABEL USERS (ADMIN/GURU)
    $q_user = mysqli_query($koneksi, "SELECT * FROM users WHERE username = '$username' LIMIT 1");
    $user = mysqli_fetch_array($q_user);

    if ($user && password_verify($password, $user['password'])) {
        session_regenerate_id(true);
        $_SESSION['login'] = true;
        $_SESSION['id_user'] = $user['id_user'];
        $_SESSION['id_guru'] = $user['id_guru'];
        $_SESSION['role'] = $user['role'];

        // Ambil Semester & TP Aktif
        $sem = mysqli_fetch_array(mysqli_query($koneksi, "SELECT id_semester FROM semester WHERE status = 'Aktif' LIMIT 1"));
        $tp = mysqli_fetch_array(mysqli_query($koneksi, "SELECT id_tp_tahun FROM tahun_pelajaran WHERE status = 'Aktif' LIMIT 1"));
        $_SESSION['id_sem_aktif'] = $sem['id_semester'] ?? 0;
        $_SESSION['id_tp_aktif'] = $tp['id_tp_tahun'] ?? 0;

        header("Location: " . (strtolower($user['role']) == 'admin' ? 'admin/dashboard.php' : 'guru/dashboard.php'));
        exit;
    } 

    // 2. CEK KE TABEL MASTER_SISWA (SISWA)
    // Catatan: Jika password di master_siswa menggunakan md5 (sesuai gambar), gunakan md5()
    $password_md5 = md5($password); 
    $q_siswa = mysqli_query($koneksi, "SELECT * FROM master_siswa WHERE username = '$username' AND password = '$password_md5' LIMIT 1");
    $siswa = mysqli_fetch_array($q_siswa);

    if ($siswa) {
        session_regenerate_id(true);
        $_SESSION['login'] = true;
        $_SESSION['role'] = 'siswa';
        $_SESSION['id_siswa'] = $siswa['id_siswa'];
        $_SESSION['nama'] = $siswa['nama'];
        $_SESSION['id_rombel'] = $siswa['id_rombel']; // Penting untuk filter jadwal

        header("Location: siswa/dashboard.php");
        exit;
    }

    // 3. JIKA TIDAK KETEMU DI KEDUANYA
    echo "<script>alert('Username atau password salah!'); window.location='login.php';</script>";

} else {
    header("Location: login.php");
}
?>