<?php namespace App\Controllers\Sistema;


use App\Controllers\BaseResourceController;
use App\Entities\Sistema\ActivityEntity;
use App\Models\CollectionModel;
use App\Models\Sistema\ActivityModel;

class Actividad extends BaseResourceController
{

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

    protected static $controllerSlug = 'activity';

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

    protected static $indexRoute = 'activityList';


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

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

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


    public function index()
    {
        checkPermission('actividad.menu');

        $viewData = [
            
            'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Paises.pais')]),
            'activityEntity' => new ActivityEntity(),
            'usingServerSideDataTable' => true,
            'logs' => $this->model->getLogs()->get()->getResultArray()[0]   // MEJORAR!!!

        ];

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

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


    public function datatable()
    {
        if ($this->request->isAJAX()) {
            $reqData = $this->request->getPost();
            if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
                $errstr = 'No data available in response to this specific request.';
                $response = $this->respond(CollectionModel::datatable([], 0, 0, $errstr), 400, $errstr);
                return $response;
            }
            $start = $reqData['start'] ?? 0;
            $length = $reqData['length'] ?? 5;
            $search = $reqData['search']['value'];
            $requestedOrder = $reqData['order']['0']['column'] ?? 1;
            $order = ActivityModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
            $dir = $reqData['order']['0']['dir'] ?? 'asc';

            $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();

            return $this->respond(CollectionModel::datatable(
                $resourceData,
                $this->model->getResource()->countAllResults(),
                $this->model->getResource($search)->countAllResults()
            ));
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }


}
