<?php
// login.php
session_start();
require 'config/database.php';

// Ambil pengaturan sekolah (Update query agar sesuai dengan tabel pengaturan_aplikasi)
$nama_sekolah_tampil = 'MA Darul Ulum Palangka Raya';
$logo_file = null;

try {
    $stmt_p = $pdo->query("SELECT nama_sekolah, logo_sekolah FROM pengaturan_aplikasi LIMIT 1");
    $pengaturan = $stmt_p->fetch();
    if ($pengaturan) {
        $nama_sekolah_tampil = htmlspecialchars($pengaturan['nama_sekolah']);
        $logo_file = $pengaturan['logo_sekolah'];
    }
} catch (PDOException $e) {
    error_log("Gagal mengambil pengaturan: " . $e->getMessage());
}

// Cek session yang sudah ada
if (isset($_SESSION['user_logged_in'])) {
    if ($_SESSION['role'] === 'admin' || $_SESSION['role'] === 'operator') {
        header("Location: admin/dashboard.php"); exit();
    } else {
        header("Location: nasabah/dashboard.php"); exit();
    }
}

$error = '';

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

    try {
        // --- LANGKAH 1: Cek di tabel USERS (Admin & Operator) ---
        $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'])) {
            session_regenerate_id(true);
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['user_logged_in'] = true;
            header("Location: admin/dashboard.php");
            exit();
        } 
        
        // --- LANGKAH 2: Jika tidak ada di users, cek di tabel SISWA (Nasabah) ---
        $stmt_s = $pdo->prepare("SELECT id_siswa, nis, nama_siswa, password FROM siswa WHERE username = ?");
        $stmt_s->execute([$username]);
        $siswa = $stmt_s->fetch();

        if ($siswa && password_verify($password, $siswa['password'])) {
            session_regenerate_id(true);
            $_SESSION['id_siswa'] = $siswa['id_siswa']; // ID Asli Siswa
            $_SESSION['username'] = $siswa['nis'];
            $_SESSION['nama_lengkap'] = $siswa['nama_siswa'];
            $_SESSION['role'] = 'siswa';
            $_SESSION['user_logged_in'] = true;
            header("Location: nasabah/dashboard.php");
            exit();
        }

        $error = 'Username atau password salah!';

    } catch (PDOException $e) {
        $error = "Terjadi masalah koneksi database.";
    }
}
?>