<?php

namespace App\Filters;

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

class AdminFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! session()->has('user_id')) {
            if ($request->isAJAX()) {
                return service('response')
                    ->setStatusCode(401)
                    ->setJSON(['success' => false, 'message' => 'Sesi habis. Silakan login kembali.']);
            }
            return redirect()->to('/login')->with('error', 'Silakan login terlebih dahulu.');
        }
        if (session('role') !== 'administrator') {
            if ($request->isAJAX()) {
                return service('response')
                    ->setStatusCode(403)
                    ->setJSON(['success' => false, 'message' => 'Akses ditolak. Hanya administrator.']);
            }
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak. Halaman ini hanya untuk administrator.');
        }
    }

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