<?php

namespace App\Controllers\Configuracion;

use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Models\Configuracion\ConfigVariableModel;
use CodeIgniter\HTTP\Response;
use Hermawan\DataTables\DataTable;

class ConfigVariables extends BaseResourceController
{

    protected $modelName = ConfigVariableModel::class;
    protected ConfigVariableModel $configVariableModel;
    protected $format = 'json';

    protected static $singularObjectName = 'Variables';
    protected static $singularObjectNameCc = 'variables';
    protected static $pluralObjectName = 'Variables';
    protected static $pluralObjectNameCc = 'variables';

    protected static $controllerSlug = 'variables';

    protected static $viewPath = 'themes/vuexy/form/configuracion/variables/';

    protected $indexRoute = 'viewVariablesList';


    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {


        parent::initController($request, $response, $logger);
        $this->configVariableModel = model(ConfigVariableModel::class);
    }


    public function index()
    {

        $viewData = [
            'currentModule' => static::$controllerSlug,
        ];

        $viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class

        return view(static::$viewPath . $this->indexRoute, $viewData);
    }
    public function store()
    {
        $data = [];
        $variableCreated = $this->configVariableModel->store($data);
        return $this->response->setJSON($variableCreated);
    }
    public function get(int $config_variable_id)
    {
        $data = $this->configVariableModel->find($config_variable_id);
        return $this->response->setJSON($data);
    }
    public function updateVariable(int $config_variable_id)
    {
        $reqData = [];
        if ($this->request->isAJAX()) {
            $reqData = $this->request->getPost();
            $status = $this->configVariableModel->update($config_variable_id, $reqData);
            return $this->response->setJSON([
                "message" => "Variable actualizada correctamente",
                "status" => $status
            ]);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }
    public function deleteVariable(int $config_variable_id): Response
    {
        return $this->response->setJSON([]);
    }
    public function datatable()
    {

        $query = $this->configVariableModel->builder()->select([
            "id",
            "name",
            "value",
            "description"
        ])->orderBy("name", "asc");
        return DataTable::of($query)
            ->add("action", fn($q) => $q->id)
            ->toJson(true);
    }
}