<?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)
    {
        $session = session();
        
        // 1. Check if user is logged in
        if (!$session->get('logged_in')) {
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }

        // 2. Check role if arguments are specified (e.g. ['wali'], ['kesantrian'])
        if (!empty($arguments)) {
            $userRole = $session->get('role');
            if (!in_array($userRole, $arguments)) {
                // Redirect unauthorized users to their correct dashboard
                switch ($userRole) {
                    case 'admin':
                        return redirect()->to('/admin/dashboard')->with('error', 'Akses ditolak. Anda dialihkan ke dashboard Admin.');
                    case 'kesantrian':
                        return redirect()->to('/kesantrian/dashboard')->with('error', 'Akses ditolak. Anda dialihkan ke dashboard Kesantrian.');
                    case 'satpam':
                        return redirect()->to('/satpam/dashboard')->with('error', 'Akses ditolak. Anda dialihkan ke dashboard Satpam.');
                    case 'wali':
                        return redirect()->to('/wali/dashboard')->with('error', 'Akses ditolak. Anda dialihkan ke dashboard Wali.');
                    default:
                        return redirect()->to('/login')->with('error', 'Role tidak valid.');
                }
            }
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do nothing
    }
}
