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

// Cek apakah user sudah login
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header("Location: ../login.php");
    exit();
}

// Cek role harus siswa
if ($_SESSION['role'] !== 'siswa') {
    // Jika admin/operator mencoba akses dashboard siswa, redirect ke dashboard admin
    if ($_SESSION['role'] === 'admin' || $_SESSION['role'] === 'operator') {
        header("Location: ../admin/dashboard.php");
        exit();
    }
    header("Location: ../login.php");
    exit();
}

// Ambil ID siswa (mendukung kedua format session)
$id_siswa = $_SESSION['user_id'] ?? $_SESSION['id_user'] ?? null;
if (!$id_siswa) {
    // Jika tidak ada ID, cari dari database berdasarkan username
    try {
        $stmt = $pdo->prepare("SELECT id_siswa FROM siswa WHERE nis = ?");
        $stmt->execute([$_SESSION['username']]);
        $data = $stmt->fetch();
        
        if ($data) {
            $_SESSION['user_id'] = $data['id_siswa'];
            $_SESSION['id_user'] = $data['id_siswa'];
            $id_siswa = $data['id_siswa'];
        } else {
            session_destroy();
            header("Location: ../login.php");
            exit();
        }
    } catch (PDOException $e) {
        session_destroy();
        header("Location: ../login.php");
        exit();
    }
}
?>