<?php

namespace App\Controllers;

use App\Controllers\Base\SarprasPetugaController as BaseSarprasPetugaController;

class SarprasPetugaController extends BaseSarprasPetugaController
{
    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);
    }

    /**
     * Get all sarpras_petugas with eager loading
     * GET /sarpras-petugas
     */
    public function index()
    {
        $this->authorizeSarpras('view');
        
        $page = max(1, (int)$this->request->query('page', 1));
        $perPage = min(100, max(1, (int)$this->request->query('per-page', 25)));
        $search = $this->request->query('search');
        
        $sortBy = $this->request->query('sort_by');
        $order = $this->request->query('order', 'asc');
        $orderBy = null;

        if ($sortBy) {
            $direction = strtolower($order) === 'desc' ? 'DESC' : 'ASC';
            $orderBy = "{$sortBy} {$direction}";
        }

        $this->model->with(['user']);

        if ($search) {
            $search = substr($search, 0, 255);
            $result = $this->model->searchPaginate($search, $page, $perPage, $orderBy);
        } else {
            $result = $this->model->paginate($page, $perPage, [], $orderBy);
        }

        if (!empty($result['data'])) {
            $this->model->loadRelations($result['data']);
        }

        return \App\Resources\SarprasPetugaResource::collection($result);
    }

    /**
     * Get single sarpras_petugas with eager loading
     * GET /sarpras-petugas/{id}
     */
    public function show()
    {
        $this->authorizeSarpras('view');
        
        $id = $this->request->param('id');
        $this->model->with(['user']);
        $petugas = $this->model->find($id);
        
        if (!$petugas) {
            throw new \Exception('Petugas tidak ditemukan', 404);
        }
        
        return \App\Resources\SarprasPetugaResource::make($petugas);
    }

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

    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();
    }
}