<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // 1. Cek apakah pengguna sudah login
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }

        // 2. Cek hak akses role (jika dibatasi di rute)
        if ($arguments) {
            $userRole = session()->get('user_role');
            if (!in_array($userRole, $arguments)) {
                $errorMsg = 'Anda tidak memiliki hak akses untuk membuka halaman tersebut.';
                
                // Kembalikan ke dashboard masing-masing role untuk mencegah loop
                switch ($userRole) {
                    case 'siswa':
                        return redirect()->to('/siswa/dashboard')->with('error', $errorMsg);
                    case 'guru':
                        return redirect()->to('/guru/dashboard')->with('error', $errorMsg);
                    case 'tata_usaha':
                        return redirect()->to('/tata-usaha/dashboard')->with('error', $errorMsg);
                    default:
                        return redirect()->to('/dashboard')->with('error', $errorMsg);
                }
            }
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Tidak diperlukan tindakan pasca-proses
    }
}
