<?php

namespace App\Controllers;

use App\Controllers\Base\SarprasItemController as BaseSarprasItemController;

class SarprasItemController extends BaseSarprasItemController
{
    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();
    }

    /**
     * Create new sarprasitem and automatically generate qr_code_string
     * POST /sarprasitems
     */
    public function store()
    {
        $this->authorizeSarpras('edit');

        $validated = $this->validate([
            'kode_barang' => 'required|string|max:50|unique:sarpras_items,kode_barang',
            'nama_barang' => 'required|string|max:100',
            'kategori' => 'required|string|max:50',
            'spesifikasi' => 'string',
            'kondisi' => 'string|max:50',
            'status' => 'string|max:20',
            'lokasi_ruang' => 'string|max:100',
            'lokasi_rak' => 'string|max:100',
            'stok_total' => 'integer',
            'stok_tersedia' => 'integer',
            'gambar' => 'string|max:255',
            'qr_code_string' => 'string|max:255',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        try {
            // Set initial stok_tersedia equal to stok_total if not provided
            if (!isset($validated['stok_tersedia'])) {
                $validated['stok_tersedia'] = $validated['stok_total'] ?? 1;
            }
            if (!isset($validated['stok_total'])) {
                $validated['stok_total'] = 1;
            }

            // Create record
            $id = $this->model->create($validated);
            
            // Auto generate qr_code_string if not set
            if (empty($validated['qr_code_string'])) {
                $qrCodeString = 'ITEM-' . $id;
                $this->model->update($id, ['qr_code_string' => $qrCodeString]);
            }

            $sarprasitem = $this->model->find($id);
            return $this->created(\App\Resources\SarprasItemResource::make($sarprasitem));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create sarprasitem', $e);
        }
    }

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

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