<?php

namespace App\Controllers;

use App\Controllers\Base\SarprasPeminjamController as BaseSarprasPeminjamController;

class SarprasPeminjamController extends BaseSarprasPeminjamController
{
    protected function authorizeSarpras(string $action)
    {
        $user = \Wibiesana\Padi\Core\Auth::user();
        if (!$user) {
            throw new \Exception('Unauthorized', 401);
        }
        
        $userId = is_array($user) ? ($user['id'] ?? $user['user_id'] ?? null) : ($user->id ?? $user->user_id ?? null);
        $role = is_array($user) ? ($user['role'] ?? null) : ($user->role ?? null);

        // Admin/Superadmin has access to all actions
        if ($role === 'superadmin' || $role === 'admin') {
            return;
        }

        // Check if the user is a registered petugas sarpras
        $isPetugas = false;
        if ($userId) {
            $petugasModel = new \App\Models\SarprasPetuga();
            $isPetugas = $petugasModel->findQuery()->where(['user_id' => $userId])->count() > 0;
        }

        if ($action === 'delete') {
            // Only admin can delete
            throw new \Exception('Forbidden: Only admin can delete data', 403);
        }

        if ($isPetugas) {
            // Petugas Sarpras can access all except delete (which is handled above)
            return;
        }

        // Guru/Siswa (teacher/student)
        if ($action === 'view') {
            return;
        }

        throw new \Exception('Forbidden: You do not have permission to perform this action', 403);
    }

    public function index()
    {
        $this->authorizeSarpras('view');
        return parent::index();
    }

    public function all()
    {
        $this->authorizeSarpras('view');
        return parent::all();
    }

    public function show()
    {
        $this->authorizeSarpras('view');
        return parent::show();
    }

    public function store()
    {
        $this->authorizeSarpras('edit');
        return parent::store();
    }

    public function update()
    {
        $this->authorizeSarpras('edit');
        return parent::update();
    }

    public function destroy()
    {
        $this->authorizeSarpras('delete');
        return parent::destroy();
    }
}