<?php namespace App\Controllers\Sistema;


use App\Controllers\BaseResourceController;
use App\Models\Sistema\SettingsModel;


class Ajustes extends BaseResourceController
{

    protected $modelName = SettingsModel::class;
    protected $format = 'json';

    protected static $controllerSlug = 'settings';

    protected static $viewPath = 'themes/vuexy/form/settings/';

    protected static string $formViewName = 'settingsForm';

    protected static $singularObjectName = 'settings';
    protected static $singularObjectNameCc = 'settings';

    protected $indexRoute = 'ajustesList';


    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        $this->viewData['pageTitle'] = lang('Provincias.moduleTitle');
        $this->viewData['usingSweetAlert'] = true;

        // Breadcrumbs (IMN)
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
            ['title' => lang("App.menu_settings"), 'route' => route_to('ajustesList'), 'active' => true]
        ];

        parent::initController($request, $response, $logger);
    }


    public function settings()
    {

        $id = 1;
        $settingsEntity = $this->model->find($id);

        if (!$settingsEntity) :
            $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Provincias.provincia')), $id]);
            return $this->redirect2listView('sweet-error', $message);
        endif;


        if ($this->request->is('post')) :

            $postData = $this->request->getPost();

            $sanitizedData = $this->sanitized($postData, true);

            $noException = true;
            if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :


                if ($this->canValidate()) :
                    try {
                        $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
                    } catch (\Exception $e) {
                        $noException = false;
                        $this->dealWithException($e);
                    }
                else:
                    $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Provincias.provincia'))]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());

                endif;

                $settingsEntity->fill($sanitizedData);

                $thenRedirect = false;
            endif;
            if ($noException && $successfulResult) :
                $id = $settingsEntity->id ?? $id;
                $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';

                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
                    else:
                        return $this->redirect2listView('sweet-success', $message);
                    endif;
                else:
                    $this->session->setFlashData('sweet-success', $message);
                endif;

            endif; // $noException && $successfulResult
        endif; // ($requestMethod === 'post')

        $this->viewData['settingsEntity'] = $settingsEntity;
        $this->viewData['formAction'] = route_to('settingsEdit');

        $this->viewData['tables'] = db_connect()->listTables();


        return $this->displayForm(__METHOD__, $id);
    } // end function settings(...)





}
