<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/config/config.php';

$error = '';

if (isset($_POST['login'])) {

    $username = trim($_POST['username']); // ADMIN = username | SEKOLAH = NPSN
    $password = trim($_POST['password']);

    if ($username == '' || $password == '') {
        $error = "Username / NPSN dan Password wajib diisi!";
    } else {

        $stmt = $conn->prepare("
            SELECT 
                id_user,
                username,
                password,
                role
            FROM users
            WHERE username = ?
              AND status = 'aktif'
            LIMIT 1
        ");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res->num_rows === 1) {

            $u = $res->fetch_assoc();

            if (password_verify($password, $u['password'])) {

                /* =====================
                   SET SESSION (WAJIB)
                ===================== */
                
				$_SESSION['login']    = true;
				$_SESSION['id_user']  = $u['id_user'];
				$_SESSION['username'] = $u['username']; // NPSN
				$_SESSION['npsn']     = $u['username']; // ✅ TAMBAHAN PENTING
				$_SESSION['role']     = $u['role'];     // admin / sekolah
				
                /* =====================
                   REDIRECT
                ===================== */
                header("Location: dashboard.php");
                exit;

            } else {
                $error = "Password salah!";
            }

        } else {
            $error = "Username / NPSN tidak terdaftar!";
        }
    }
}
?>

