<?php

namespace App\Controllers;

use App\Controllers\Base\RoleController as BaseController;

class RoleController extends BaseController
{
    public function store()
    {
        $validated = $this->validate([
            'name' => 'required|string|max:50|unique:role,name',
            'description' => 'string|max:255',
            'permissions' => 'nullable',
            'is_active' => 'integer',
            'guard_name' => 'string|max:20',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        // Ensure permissions is string for DB if it's an array
        if (isset($validated['permissions']) && is_array($validated['permissions'])) {
            $validated['permissions'] = json_encode($validated['permissions']);
        }
        
        try {
            $id = $this->model->create($validated);
            $this->model->with(['createdBy:id,username', 'updatedBy:id,username']);
            $role = $this->model->find($id);
            return $this->created(\App\Resources\RoleResource::make($role));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create role', $e);
        }
    }

    public function update()
    {
        $id = $this->request->param('id');
        $role = $this->model->find($id);
        
        if (!$role) {
            throw new \Exception('Role not found', 404);
        }
        
        $validated = $this->validate([
            'name' => 'required|string|max:50|unique:role,name,' . $id,
            'description' => 'string|max:255',
            'permissions' => 'nullable',
            'is_active' => 'integer',
            'guard_name' => 'string|max:20',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);

        // Ensure permissions is string for DB if it's an array
        if (isset($validated['permissions']) && is_array($validated['permissions'])) {
            $validated['permissions'] = json_encode($validated['permissions']);
        }
        
        try {
            $this->model->update($id, $validated);
            $this->model->with(['createdBy:id,username', 'updatedBy:id,username']);
            return \App\Resources\RoleResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update role', $e);
        }
    }
}
