<?php

namespace App\Controllers\Configuracion;

use App\Controllers\BaseController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;

use App\Entities\Configuracion\Imposicion;
use App\Models\Configuracion\ImposicionEsquemaModel;
use App\Models\Configuracion\ImposicionModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use Hermawan\DataTables\DataTable;
use Psr\Log\LoggerInterface;

class Imposiciones extends BaseController
{

    protected $modelName = ImposicionModel::class;
    protected ImposicionModel $model;
    protected ImposicionEsquemaModel $imposicionEsquemaModel;
    protected static $controllerSlug = 'imposiciones';
    protected $format = 'json';

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

    protected $indexRoute = 'imposicionList';
    protected array $viewData = [];
    protected Validation $validation;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        $this->viewData['pageTitle'] = lang('Imposiciones.moduleTitle');
        $this->viewData['usingSweetAlert'] = true;
        $this->model = model($this->modelName);
        $this->validation = service("validation");
        $this->imposicionEsquemaModel = model(ImposicionEsquemaModel::class);
        parent::initController($request, $response, $logger);
    }


    public function index()
    {

        $viewData = [
            'currentModule' => static::$controllerSlug,
            'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Imposiciones.imposicion')]),
            'imposicion' => new Imposicion(),
            'usingServerSideDataTable' => true,

        ];
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => true],

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

        return view(static::$viewPath . 'viewImposicionList', $viewData);
    }


    public function add()
    {
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => true],

        ];
        return view(static::$viewPath . 'viewImposicionNewForm', $this->viewData);
    }
    public function add_esquema()
    {
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => true],
        ];
        $this->viewData["imposicion_esquema"] = null;

        return view(static::$viewPath . 'viewImposicionEsquemaForm', $this->viewData);
    }
    public function edit($imposicion_id = null)
    {
        if ($imposicion_id) {
            $this->viewData["imposicion"] = $this->model->find($imposicion_id);
            $this->viewData['breadcrumb'] = [
                ['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => false],
                ['title' => $this->viewData["imposicion"]->full_name, 'route' => route_to("updateImposicionForm", $imposicion_id), 'active' => true],

            ];
        }
        return view(static::$viewPath . 'viewImposicionForm', $this->viewData);
    }
    public function edit_imposicion_esquema($imposicion_esquema_id = null)
    {
        if ($imposicion_esquema_id) {
            $this->viewData["imposicion_esquema"] = $this->imposicionEsquemaModel->find($imposicion_esquema_id);
            $this->viewData['breadcrumb'] = [
                ['title' => lang("App.menu_imposiciones"), 'route' => route_to("imposicionList"), 'active' => false],
                ['title' => $this->viewData["imposicion_esquema"]->name, 'route' => route_to("updateImposicionEsquemaForm", $imposicion_esquema_id), 'active' => true],

            ];
        }
        return view(static::$viewPath . 'viewImposicionEsquemaForm', $this->viewData);
    }
    public function update($imposicion_id = null)
    {
        if ($imposicion_id) {
            $bodyData = $this->request->getPost();
            if(isset($bodyData["imposicion_esquema_id"])){
                if($bodyData["imposicion_esquema_id"] == ""){
                    $bodyData["imposicion_esquema_id"] = null;
                }
            }
            $status = $this->model->update($imposicion_id, $bodyData);
            if ($status) {
                $imposicionEntity = $this->model->find($imposicion_id);
            } else {
                return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->model->errors(), "status" => true])->setStatusCode(400);
            }
            return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status, "data" => $imposicionEntity]);
        } else {
            return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "message" => "", "status" => false])->setStatusCode(400);
        }
    }
    public function update_imposicion_esquema($imposicion_esquema_id = null)
    {
        if ($imposicion_esquema_id) {
            $bodyData = $this->request->getPost();
            $status = $this->imposicionEsquemaModel->update($imposicion_esquema_id, $bodyData);
            if ($status) {
                $imposicionEsquemaEntity = $this->imposicionEsquemaModel->find($imposicion_esquema_id);
            } else {
                return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->imposicionEsquemaModel->errors(), "status" => true])->setStatusCode(400);
            }
            return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => $status, "data" => $imposicionEsquemaEntity]);
        } else {
            return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "message" => "", "status" => false])->setStatusCode(400);
        }
    }
    public function delete($imposicion_id = null)
    {
        $status = $this->model->delete($imposicion_id);
        return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => true]);
    }
    public function delete_imposicion_esquema($imposicion_esquema_id = null)
    {
        $status = $this->imposicionEsquemaModel->delete($imposicion_esquema_id);
        return $this->response->setJSON(["message" => lang("App.user_alert_delete"), "status" => $status]);
    }


    public function datatable()
    {
        $q = $this->model->queryDatatable();
        return DataTable::of($q)
            ->add('esquema', fn($q) => ["imposicionId" => $q->id,"esquemaId" => $q->esquemaId, "esquemaName" => $q->esquemaName])
            ->add(
                'action',
                fn($q) => "<div class='btn-group btn-group-md gap-2 w-100 d-flex justify-space-between'>" . ImposicionModel::datatable_buttons($q->id) . "</div>"
            )
            ->toJson(true);
    }
    public function datatable_imposicion_esquema()
    {
        $q = $this->imposicionEsquemaModel->queryDatatable();
        return DataTable::of($q)
            ->add(
                'action',
                fn($q) => "<div class='btn-group btn-group-md gap-2'>" . ImposicionEsquemaModel::datatable_buttons($q->id) . "</div>"
            )
            ->toJson(true);
    }


    public function selectImposicion()
    {
        $data = $this->model->querySelect($this->request->getGet('q'));
        return $this->response->setJSON($data);
    }
    public function selectImposicionEsquema()
    {
        $data = $this->imposicionEsquemaModel->querySelect($this->request->getGet('q'));
        return $this->response->setJSON($data);
    }
    public function find_imposicion(int $imposicion_id)
    {
        $imposicionEntity = $this->model->find($imposicion_id)->withImposicionEsquema();
        return $this->response->setJSON($imposicionEntity);
    }
    public function find_imposicion_esquema(int $imposicion_esquema_id)
    {
        $imposicionEsquemaEntity = $this->imposicionEsquemaModel->find($imposicion_esquema_id);
        return $this->response->setJSON($imposicionEsquemaEntity);
    }
    public function create()
    {
        $bodyData = $this->request->getPost();
        $createdId = $this->model->insert($bodyData);
        if ($createdId) {
            return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true]);
        } else {
            return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->model->errors(), "status" => true])->setStatusCode(400);
        }
    }
    public function create_imposicion_esquema()
    {
        $bodyData = $this->request->getPost();
        $createdId = $this->imposicionEsquemaModel->insert($bodyData);
        if ($createdId) {
            return $this->response->setJSON(["message" => lang("App.global_alert_save_success"), "status" => true]);
        } else {
            return $this->response->setJSON(["message" => lang("App.global_alert_save_error"), "errors" => $this->imposicionEsquemaModel->errors(), "status" => true])->setStatusCode(400);
        }
    }
}
