<?php
declare(strict_types=1);

namespace App\Controller\Admin;

use App\Controller\AppController;
use Cake\Event\EventInterface;
use App\Text\Messages;

/**
 * Proyectos Controller
 *
 * @property \App\Model\Table\ProyectosTable $Proyectos
 */
class ProyectosController extends AppController
{
    public $texts;
    public function beforeFilter( EventInterface $event ) {
        parent::beforeFilter( $event );
        $this->viewBuilder()->setLayout('admin/default');
        $this->texts = [
            'article' => __('El'),
            'entity' => __('proyecto'),
            'article_lower' => __('el'),
        ];
    }
    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index()
    {
        $companies = $this->Proyectos->Empresas->find('list', limit: 200)->all();
        $this->set(compact('companies'));
    }
    public function list(){
        $this->viewBuilder()->setLayout("ajax");
        $projects = [];
        if($this->request->is("ajax"))
        {
            $conditions = [];
            $companyId = @$this->request->getQuery('company_id');
            if(!empty($companyId))
            {
                $conditions['Proyectos.empresa_id'] = $companyId;
            }
            $projects = $this->Proyectos->find('all',
                [
                    'fields' => [
                        'id',
                        'nombre',
                        'descripcion',
                        'activo',
                        'empresa_id',
                    ],
                    'conditions' => $conditions,
                    'contain' => [
                        'Empresas' => [
                            'fields' => [
                                'id',
                                'nombre',
                            ]
                        ]
                    ]
                ]
            );
        }
        $this->response = $this->response->withType('json');
        $this->response = $this->response->withStringBody(json_encode(["data" => $projects]));
        return $this->response;
    }

    /**
     * View method
     *
     * @param string|null $id Proyecto id.
     * @return \Cake\Http\Response|null|void Renders view
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $proyecto = $this->Proyectos->get($id, contain: ['Empresas', 'PalabrasClaves']);
        $this->set(compact('proyecto'));
    }

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $this->viewBuilder()->setClassName('Ajax.Ajax');
        $project = $this->Proyectos->newEmptyEntity();
        if ($this->request->is('post')) {
            $data = $this->request->getData();
            $data['palabras_claves'] = $this->Proyectos->dataKeyWords($data);
            $project = $this->Proyectos->patchEntity($project, $data);
            if(empty($project->palabras_claves))
            {
                $project->setError('palabras_claves', Messages::get('REQUIRED'));
            }
            $saveProject = $this->Proyectos->save($project, ['associated' => ['PalabrasClaves']]);
            if ($saveProject)
            {
                $this->Flash->success(Messages::success('add', $this->texts['article'], $this->texts['entity']));
            }
            else
            {
                $this->Flash->error(Messages::error('add', $this->texts['article_lower'], $this->texts['entity']));
            }
        }
        $companies = $this->Proyectos->Empresas->find('list', limit: 200)->all();
        $this->set(compact('project', 'companies'));
    }

    /**
     * Edit method
     *
     * @param string|null $id Proyecto id.
     * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $this->viewBuilder()->setClassName('Ajax.Ajax');
        $project = $this->Proyectos->get($id, contain: ['PalabrasClaves']);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $data = $this->request->getData();
            $data['palabras_claves'] = $this->Proyectos->dataKeyWords($data);
            $project = $this->Proyectos->patchEntity($project, $data);
            if(empty($project->palabras_claves))
            {
                $project->setError('palabras_claves', Messages::get('REQUIRED'));
            }
            $saveProject = $this->Proyectos->save($project, ['associated' => ['PalabrasClaves']]);
            if ($saveProject)
            {
                $this->Flash->success(Messages::success('edit', $this->texts['article'], $this->texts['entity']));
            }
            else
            {
                $this->Flash->error(Messages::error('edit', $this->texts['article_lower'], $this->texts['entity']));
            }
        }
        $companies = $this->Proyectos->Empresas->find('list', limit: 200)->all();
        $this->set(compact('project', 'companies'));
    }

    /**
     * Delete method
     *
     * @param string|null $id Proyecto id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $success = null;
        $this->viewBuilder()->setClassName('Ajax.Ajax');
        $this->request->allowMethod(['post', 'delete']);
        $project = $this->Proyectos->get($id);
        if ($this->Proyectos->delete($project)) {
            $this->Flash->success(Messages::success('delete', $this->texts['article'], $this->texts['entity']));
            $success = true;
        } else {
            $this->Flash->error(Messages::error('delete', $this->texts['article_lower'], $this->texts['entity']));
            $success = false;
        }
        $this->set(compact('success'));
    }
}
