<?php
namespace App\Controller;

use App\Controller\AppsController;
use Cake\I18n\I18n;
use Cake\ORM\TableRegistry;
use DateTime;
use Cake\ORM\Query;

/**
 * Categories Controller
 *
 * @property \App\Model\Table\CategoriesTable $Categories
 */
class CategoriesController extends AppsController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {   
        $page_limit=10;
        if (isset($this->request->query['page_limit'])) {
            $page_limit= $this->request->query('page_limit');
        }
       
        $this->paginate = [
            'limit' => $page_limit,
            'sortWhitelist' => [
                'Categories.created_on', 'Categories.id', 'Categories.name', 'Categories.modified_on'
            ],
            'order' => [
                'Categories.created_on' => 'desc'
            ]
        ];

        $search = '';
        if (isset($this->request->query['search'])) {
            $search = $this->request->query('search');
        }

        $categories = $this->Categories->find('all')->where([
            'Categories.name LIKE' => '%' . $search . '%'
        ]);

        $categories = $this->paginate($categories);

        $this->set(compact('categories'));
        $this->set('_serialize', ['categories']);

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('module_pages', $this->getPages());
        $this->set('bulk_actions', [BULK_ACTION_DELETE => "Move to trash"]);
        $this->set('current_module', $this->getModules());
        $this->set('sub_modules', $this->getSubModules());
        $this->set('user_permission', $user_permissions);
        $this->set('searchText', $search);
        $this->set('page_limit', $page_limit);
        $this->viewBuilder()->layout("custom_layout");
    }

    /**
     * View method
     *
     * @param string|null $id Category id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $category = $this->Categories->get($id, [
            'contain' => []
        ]);

        $this->set('category', $category);
        $this->set('_serialize', ['category']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $category = $this->Categories->newEntity();
        if ($this->request->is('post')) {
            $category = $this->Categories->patchEntity($category, $this->request->data);
            $category->created_on = date('Y-m-d h:i:s');
            $category->status = 1;
            if ($this->Categories->save($category)) {
                $this->Flash->success(__('The category has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The category could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('category'));
        $this->set('_serialize', ['category']);

        $ModulesTable = TableRegistry::get('modules');
        $modules = $ModulesTable->find('list');
        // $subModules = $this->Pages->SubModules->find('list', ['limit' => 200]);
        $this->set(compact('page', 'subModules','modules'));
        // // $this->set('_serialize', ['page']);
        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('module_pages', $this->getPages());
        $this->set('current_module', $this->getModules());
        $this->set('sub_modules', $this->getSubModules());
        $this->set('user_permission', $user_permissions);
        $this->viewBuilder()->layout("custom_layout");
    }

    /**
     * Edit method
     *
     * @param string|null $id Category id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $category = $this->Categories->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $category = $this->Categories->patchEntity($category, $this->request->data);
            $category->modified_on = date('Y-m-d h:i:s');
            if ($this->Categories->save($category)) {
                $this->Flash->success(__('The category has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The category could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('category'));
        $this->set('_serialize', ['category']);

        $ModulesTable = TableRegistry::get('modules');
        $modules = $ModulesTable->find('list');
        // $subModules = $this->Pages->SubModules->find('list', ['limit' => 200]);
        $this->set(compact('page', 'subModules','modules'));
        // // $this->set('_serialize', ['page']);
        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('module_pages', $this->getPages());
        $this->set('current_module', $this->getModules());
        $this->set('sub_modules', $this->getSubModules());
        $this->set('user_permission', $user_permissions);
        $this->viewBuilder()->layout("custom_layout");
    }

    /**
     * Delete method
     *
     * @param string|null $id Category id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        // check for subCategories
        $subCategories = [];
        $subCategoriesTable = TableRegistry::get('SubCategories');
        $subCategories = $subCategoriesTable->find('all')->where([
            'SubCategories.category_id' => $id
        ])->toArray();

        // check for Forms
        $forms = [];
        $formsTable = TableRegistry::get('Forms');
        $forms = $formsTable->find('all')->where([
            'Forms.category_id' => $id
        ])->toArray();

        if(empty($subCategories))
        {
            if(empty($forms))
            {
                $this->request->allowMethod(['post', 'delete']);
                $category = $this->Categories->get($id);
                if ($this->Categories->delete($category)) {
                    $this->Flash->success(__('The category has been deleted.'));
                } else {
                    $this->Flash->error(__('The category could not be deleted. Please, try again.'));
                }
            } else {
                $this->Flash->error(__('The category is assigned to a Form so could not be deleted.'));
            }
        } else {
            $this->Flash->error(__('The category is assigned to a Sub-Category so could not be deleted.'));
        }

                

        return $this->redirect(['action' => 'index']);
    }

    
}
