<?php

namespace App\Controllers;

use Wibiesana\Padi\Core\Controller;
use Wibiesana\Padi\Core\Request;
use App\Models\SarprasBangunan;
use App\Resources\SarprasBangunanResource;

class SarprasBangunanController extends Controller
{
    protected SarprasBangunan $model;
    
    public function __construct(?Request $request = null)
    {
        parent::__construct($request);
        $this->model = new SarprasBangunan();
    }

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

        if ($role === 'superadmin' || $role === 'admin') {
            return;
        }

        $isPetugas = false;
        if ($userId) {
            $petugasModel = new \App\Models\SarprasPetugas();
            $isPetugas = $petugasModel->findQuery()->where(['user_id' => $userId])->count() > 0;
        }

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

        if ($isPetugas) {
            return;
        }

        if ($action === 'view') {
            return;
        }

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

    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}";
        }

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

        return SarprasBangunanResource::collection($result);
    }

    public function all()
    {
        $this->authorizeSarpras('view');
        
        $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}";
        }

        if ($search) {
             return SarprasBangunanResource::collection($this->model->search($search, $orderBy));
        }
        return SarprasBangunanResource::collection($this->model->all(['*'], $orderBy));
    }

    public function show()
    {
        $this->authorizeSarpras('view');
        
        $id = $this->request->param('id');
        $item = $this->model->find($id);
        
        if (!$item) {
            throw new \Exception('Bangunan not found', 404);
        }
        
        // Eager load relations
        $temp = [$item];
        $this->model->loadRelations($temp);
        $item = $temp[0];
        
        return SarprasBangunanResource::make($item);
    }

    public function store()
    {
        $this->authorizeSarpras('edit');

        $validated = $this->validate([
            'kode_bangunan' => 'required|string|max:50|unique:sarpras_bangunan,kode_bangunan',
            'nama_bangunan' => 'required|string|max:100',
            'deskripsi' => 'string',
            'luas_tanah' => 'numeric',
            'jumlah_lantai' => 'integer',
            'kondisi' => 'string|max:50',
            'tahun_pembangunan' => 'integer'
        ]);
        
        try {
            $id = $this->model->create($validated);
            $item = $this->model->find($id);
            return $this->created(SarprasBangunanResource::make($item));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create bangunan', $e);
        }
    }

    public function update()
    {
        $this->authorizeSarpras('edit');
        
        $id = $this->request->param('id');
        $item = $this->model->find($id);
        
        if (!$item) {
            throw new \Exception('Bangunan not found', 404);
        }
        
        $validated = $this->validate([
            'kode_bangunan' => 'required|string|max:50|unique:sarpras_bangunan,kode_bangunan,' . $id,
            'nama_bangunan' => 'required|string|max:100',
            'deskripsi' => 'string',
            'luas_tanah' => 'numeric',
            'jumlah_lantai' => 'integer',
            'kondisi' => 'string|max:50',
            'tahun_pembangunan' => 'integer'
        ]);
        
        try {
            $this->model->update($id, $validated);
            return SarprasBangunanResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update bangunan', $e);
        }
    }

    public function destroy()
    {
        $this->authorizeSarpras('delete');
        
        $id = $this->request->param('id');
        $item = $this->model->find($id);
        
        if (!$item) {
            throw new \Exception('Bangunan not found', 404);
        }
        
        try {
            $this->model->delete($id);
            return $this->noContent();
        } catch (\PDOException $e) {
            $this->databaseError('Failed to delete bangunan', $e);
        }
    }
}
