<?php

namespace App\Controllers;

use Wibiesana\Padi\Core\Controller;
use Wibiesana\Padi\Core\Request;
use App\Models\SarprasRuangan;
use App\Resources\SarprasRuanganResource;

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

    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');
        $bangunanId = $this->request->query('bangunan_id');
        
        $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 {
            $where = [];
            if ($bangunanId) {
                $where['bangunan_id'] = $bangunanId;
            }
            $result = $this->model->paginate($page, $perPage, $where, $orderBy);
        }

        // Make sure bangunan_nama is loaded for data table list
        if (!empty($result['data'])) {
            $db = \Wibiesana\Padi\Core\DatabaseManager::connection();
            foreach ($result['data'] as &$row) {
                if (empty($row['bangunan_nama']) && !empty($row['bangunan_id'])) {
                    $b = $db->query("SELECT nama_bangunan FROM sarpras_bangunan WHERE id = " . (int)$row['bangunan_id'])->fetch();
                    $row['bangunan_nama'] = $b ? $b['nama_bangunan'] : null;
                }
            }
        }

        return SarprasRuanganResource::collection($result);
    }

    public function all()
    {
        $this->authorizeSarpras('view');
        
        $search = $this->request->query('search');
        $bangunanId = $this->request->query('bangunan_id');
        $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 SarprasRuanganResource::collection($this->model->search($search, $orderBy));
        }

        $where = [];
        if ($bangunanId) {
            $where['bangunan_id'] = $bangunanId;
        }
        return SarprasRuanganResource::collection($this->model->all($where, $orderBy));
    }

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

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

        $validated = $this->validate([
            'bangunan_id' => 'required|integer',
            'kode_ruangan' => 'required|string|max:50|unique:sarpras_ruangan,kode_ruangan',
            'nama_ruangan' => 'required|string|max:100',
            'tipe_ruangan' => 'string|max:50',
            'lantai' => 'integer',
            'kapasitas' => 'integer',
            'luas' => 'numeric',
            'kondisi' => 'string|max:50',
            'keterangan' => 'string'
        ]);
        
        try {
            $id = $this->model->create($validated);
            $item = $this->model->find($id);
            return $this->created(SarprasRuanganResource::make($item));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create ruangan', $e);
        }
    }

    public function update()
    {
        $this->authorizeSarpras('edit');
        
        $id = $this->request->param('id');
        $item = $this->model->find($id);
        
        if (!$item) {
            throw new \Exception('Ruangan not found', 404);
        }
        
        $validated = $this->validate([
            'bangunan_id' => 'required|integer',
            'kode_ruangan' => 'required|string|max:50|unique:sarpras_ruangan,kode_ruangan,' . $id,
            'nama_ruangan' => 'required|string|max:100',
            'tipe_ruangan' => 'string|max:50',
            'lantai' => 'integer',
            'kapasitas' => 'integer',
            'luas' => 'numeric',
            'kondisi' => 'string|max:50',
            'keterangan' => 'string'
        ]);
        
        try {
            $this->model->update($id, $validated);
            return SarprasRuanganResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update ruangan', $e);
        }
    }

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