<?php
namespace App\Controller;

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

/**
 * SubCategories Controller
 *
 * @property \App\Model\Table\SubCategoriesTable $SubCategories
 */
class SubCategoriesController extends AppsController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        // $subCategories = $this->paginate($this->SubCategories);

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

        $page_limit=10;
        if (isset($this->request->query['page_limit'])) {
            $page_limit= $this->request->query('page_limit');
        }
       
        $this->paginate = [
            'limit' => $page_limit,
            'contain' => ['Categories'],
            'sortWhitelist' => [
                'Categories.name','SubCategories.created_on', 'SubCategories.id', 'SubCategories.name', 'SubCategories.modified_on'
            ],
            'order' => [
                'SubCategories.created_on' => 'desc'
            ]
        ];

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

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

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

        $this->set(compact('subCategories'));
        $this->set('_serialize', ['subCategories','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 Sub Category id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $subCategory = $this->SubCategories->get($id, [
            'contain' => []
        ]);

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

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

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The sub category could not be saved. Please, try again.'));
            }
        }
        $categoriesTable = TableRegistry::get('Categories');
        $categories = $categoriesTable->find('list')->where([
            'Categories.status' => 1
        ]);
        $this->set(compact('categories'));

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

        $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->viewBuilder()->layout("custom_layout");
    }

    /**
     * Edit method
     *
     * @param string|null $id Sub 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)
    {
        $subCategory = $this->SubCategories->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $subCategory = $this->SubCategories->patchEntity($subCategory, $this->request->data);
            $subCategory->modified_on = date('Y-m-d h:i:s');
            if ($this->SubCategories->save($subCategory)) {
                $this->Flash->success(__('The sub category has been saved.'));

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

        $categoriesTable = TableRegistry::get('Categories');
        $categories = $categoriesTable->find('list')->where([
            'Categories.status' => 1
        ]);
        $this->set(compact('categories'));

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

        $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->viewBuilder()->layout("custom_layout");
    }

    /**
     * Delete method
     *
     * @param string|null $id Sub 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 Forms
        $forms = [];
        $formsTable = TableRegistry::get('Forms');
        $forms = $formsTable->find('all')->where([
            'Forms.sub_category_id' => $id
        ])->toArray();

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

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