<?php
declare(strict_types=1);

namespace App\Controller;

use App\Controller\AppController;
use Cake\Log\Log;
use Cake\Http\Exception\NotFoundException;
use cake\ORM\TableRegistry;
use Cake\Utility\Inflector;
use Cake\Utility\Text;
use Cake\I18n\Time;
use Cake\Event\EventInterface;
use Cake\Core\Configure;
use Cake\Http\Response;
/**
 * Menus Controller
 *
 * @property \App\Model\Table\MenusTable $Menus
 * @method \App\Model\Entity\Menu[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class MenusController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        $this->paginate = [
            'limit' => 50
        ];
    }

    public function beforeFilter(EventInterface $event)
    {
        parent::beforeRender($event);
    }

    public function isAuthorized($user)
    {
        return true;
    }
    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index()
    {

    }

    public function addSubMenu($section = null, $id = null)
    {
        $menuDetails = [];
        $pageTitle = '';

        if (!empty($section)) {
            $menuDetails = $this->Menus->find()
                ->where(['slug' => $section])
                ->firstOrFail(); // Use firstOrFail to handle non-existent sections

            $pageTitle = ucwords(str_replace('-', ' ', $menuDetails->name));
        }

        $menu = $this->Menus->newEmptyEntity();
        $parentData = [];

        if ($this->request->is('post')) {
            $data = $this->request->getData();
            $image_path = $this->request->getData('image_path');
            $imageSize = $image_path->getSize();

            $count = $this->Menus->find()
                ->where(['slug' => $section, 'parent_menu_id' => $id])
                ->count();
            $ps = ($count >= 1) ? '-' . $count : '';

            $data['slug'] = Text::slug(strtolower($data['name'])) . $ps;

            if ($imageSize > 0) {
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $data['image_path']);

                if (!empty($fileOK['urls'])) {
                    $data['image_path'] = substr(
                        $fileOK['file_path'][0],
                        Configure::read('IMAGE_PRELENGTH'),
                        strlen($fileOK['file_path'][0])
                    );
                }
            } else {
                $data['image_path'] = 'temp';
            }

            $menu = $this->Menus->patchEntity($menu, $data);

            if ($this->Menus->save($menu)) {
                return $this->redirect(['controller' => $section, 'action' => 'pendingSubMenu', $menuDetails->id]);
            } else {
                $this->Flash->error(__('The Menu could not be saved. Please, try again.'));
            }

        }

        $pmid = $id;
        $pageSubTitle = 'Sub Menu';
        $actiontitle = 'SubMenu';
        $this->set(compact('menu', 'actiontitle', 'pmid', 'pageTitle', 'pageSubTitle'));
    }

    public function editSubMenu($section = null, $id = null)
    {

        $menuDetails = [];
        $pageTitle = '';

        // Fetch the submenu by its ID
        $menu = $this->Menus->get($id);

        if (empty($menu)) {
            $this->Flash->error(__('Submenu not found.'));
            return $this->redirect(['action' => 'index']);
        }

        if (!empty($section)) {
            $menuDetails = $this->Menus->find()
                ->where(['slug' => $section])
                ->first(); // Fetch section details if section is provided
            if ($menuDetails) {
                $pageTitle = ucwords(str_replace('-', ' ', $menuDetails->name));
            }
        }

        if ($this->request->is(['post', 'patch', 'put'])) {
            $data = $this->request->getData();
            $image_path = $this->request->getData('image_path');
            $imageSize = $image_path->getSize();

            $count = $this->Menus->find()
                ->where(['slug' => $section, 'parent_menu_id' => $id])
                ->count();

            $ps = ($count >= 1) ? '-' . $count : '';
            $data['slug'] = Text::slug(strtolower($data['name'])) . $ps;

            // Check if there is an image and then update the image path
            if ($imageSize > 0) {
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $data['image_path']);

                if (!empty($fileOK['urls'])) {
                    $data['image_path'] = substr(
                        $fileOK['file_path'][0],
                        Configure::read('IMAGE_PRELENGTH'),
                        strlen($fileOK['file_path'][0])
                    );
                }
            } else {
                $data['image_path'] = $data['old_image'];
            }

            $menu = $this->Menus->patchEntity($menu, $data);
            $menu->status = 2;

            if ($this->Menus->save($menu)) {
                $this->Flash->success(__('The Menu has been updated.'));
                return $this->redirect(['controller' => $section, 'action' => 'editedSubMenu', $menuDetails->id]);
            } else {
                $this->Flash->error(__('The Menu could not be saved. Please, try again.'));
            }
        }

        $pageSubTitle = 'Edit Sub Menu';
        $actiontitle = 'EditSubMenu';
        $this->set(compact('menu', 'actiontitle', 'pageTitle', 'pageSubTitle'));
    }
    public function subMenus($section = null, $id)
    {
        $pageTitle = 'Sub Menu';

        $subMenulistings = $this->Menus->find('all')->where(['parent_menu_id' => $id]);
        $listings = $this->paginate($subMenulistings);
        $actiontitle = 'SubMenu';
        $this->set(compact('pageTitle', 'listings', 'actiontitle'));
        $this->render('sub-menu-listings');
    }

    public function pendingSubMenu($section = null, $id = null)
    {
        // $listings = $this->Menus->find( 'all' )->where( [ 'parent_menu_id'=>$id ] );
        $listings = $this->Menus->find('all', [
            'conditions' => [
                'parent_menu_id' => $id,
                'status' => 0
            ]
        ]);

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

        $pageTitle = 'Sub Menu';
        $actiontitle = 'SubMenu';
        $this->set(compact('actiontitle', 'pageTitle', 'listings'));
    }

    public function enabledSubMenu($section = null, $id = null)
    {
        $listings = $this->Menus->find('all')->where(['parent_menu_id' => $id]);
        $listings = $this->Menus->find('all', [
            'conditions' => [
                'parent_menu_id' => $id,
                'status' => 1
            ]
        ]);

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

        $pageSubTitle = 'Sub Menu';
        $actiontitle = 'SubMenu';
        $pageTitle = 'Sub Menu';

        $this->set(compact('actiontitle', 'pageTitle', 'pageSubTitle', 'listings'));
    }

    public function disabledSubMenu($section = null, $id = null)
    {
        $listings = $this->Menus->find('all')->where(['parent_menu_id' => $id]);
        $listings = $this->Menus->find('all', [
            'conditions' => [
                'parent_menu_id' => $id,
                'status' => 99
            ]
        ]);

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

        $pageTitle = 'Sub Menu';
        $actiontitle = 'SubMenu';
        $this->set(compact('actiontitle', 'pageTitle', 'listings'));
    }

    public function editedSubMenu($section = null, $id = null)
    {
        // $listings = $this->Menus->find( 'all' )->where( [ 'parent_menu_id'=>$id ] );
        $listings = $this->Menus->find('all', [
            'conditions' => [
                'parent_menu_id' => $id,
                'status' => 2
            ]
        ]);

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

        $pageSubTitle = 'Sub Menu';
        $actiontitle = 'SubMenu';
        $pageTitle = 'Sub Menu';

        $this->set(compact('actiontitle', 'pageTitle', 'pageSubTitle', 'listings'));
    }
    public function enableMenu($section = null, $id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['status' => 1], ['id' => $id]);
            $this->Flash->success(__('Menu has been ENABLED successfully.'));
        }

        return $this->redirect($this->referer());
    }

    public function disableMenu($section = null, $id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['status' => 99], ['id' => $id]);
            $this->Flash->success(__('Menu has been DISABLED successfully.'));
        }

        return $this->redirect($this->referer());
    }

    public function showMenuOnHome($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_home' => 1], ['id' => $id]);
            $this->Flash->success(__('Menu successfully showing on homepage.'));
        }

        return $this->redirect($this->referer());
    }

    public function removeMenuFromHome($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_home' => 0], ['id' => $id]);
            $this->Flash->success(__('Menu has successfully shows on footer.'));
        }

        return $this->redirect($this->referer());
    }

    public function showMenuOnFooter($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_footer' => 1], ['id' => $id]);
            $this->Flash->success(__('Menu successfully showing on homepage.'));
        }

        return $this->redirect($this->referer());
    }

    public function removeMenuFooter($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_footer' => 0], ['id' => $id]);
            $this->Flash->success(__('Menu has been removed from the footer.'));
        }

        return $this->redirect($this->referer());
    }

    public function subSubMenus($section = null, $id = null)
    {
        $listings = $this->Menus->findSubSubMenus($id);
        $pageSubTitle = ' Sub Sub Menu';
        $actiontitle = 'SubSubMenu';
        $listings = $this->paginate($listings);
        $this->set(compact('listings', 'actiontitle', 'pageSubTitle'));
        $this->render('sub-sub-menu-listings');
    }

    public function addSubSubMenu($section = null, $id = null)
    {
        $parentMenus = $this->Menus->find('all')->where(['parent_menu_id' => $id])->combine('id', 'name');

        $menu = $this->Menus->newEmptyEntity();

        $parentData = [];

        if ($this->request->is('post')) {
            $data = $this->request->getData();
            $image_path = $this->request->getData('image_path');
            $imageSize = $image_path->getSize();

            $count = $this->Menus->find('All')->where(['slug' => $section, 'parent_menu_id' => $id])->count();
            $ps = ($count >= 1) ? '-' . $count : '';

            $data['slug'] = Text::slug(strtolower($data['name'])) . $ps;

            if ($imageSize > 0) {
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $data['image_path']);

                if (!empty($fileOK['urls'])) {
                    $data['image_path'] = substr(
                        $fileOK['file_path'][0],
                        Configure::read('IMAGE_PRELENGTH'),
                        strlen($fileOK['file_path'][0])
                    );
                }
            } else {
                $data['image_path'] = 'temp';
            }

            $menu = $this->Menus->patchEntity($menu, $data);

            if ($this->Menus->save($menu)) {
                return $this->redirect(['controller' => $section, 'action' => 'pendingSubSubMenu', $id]);
            } else {
                $this->Flash->error(__('The sub sub Menu could not be saved. Please, try again.'));
            }
        }

        $pageSubTitle = 'Sub Sub Menu';
        $actiontitle = 'SubSubMenu';
        $this->set(compact('parentMenus', 'menu', 'actiontitle', 'pageSubTitle'));
    }

    public function editSubSubMenu($section = null, $id = null)
    {
        $menuDetails = [];
        $pageTitle = '';

        $pmid = $this->Menus->find('All')->where(['slug' => $section])->first()->id;
        $parentMenus = $this->Menus->find('all')->where(['parent_menu_id' => $pmid])->combine('id', 'name');
        $menu = $this->Menus->get($id);

        if ($this->request->is(['post', 'patch', 'put'])) {

            $data = $this->request->getData();
            $image_path = $this->request->getData('image_path');
            $imageSize = $image_path->getSize();

            $sectionDetails = $this->Menus->find('All')->where(['slug' => $section])->first();

            // Check if there is an image and then update the image path
            if ($imageSize > 0) {
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $data['image_path']);

                if (!empty($fileOK['urls'])) {
                    $data['image_path'] = substr(
                        $fileOK['file_path'][0],
                        Configure::read('IMAGE_PRELENGTH'),
                        strlen($fileOK['file_path'][0])
                    );
                }
            } else {
                $data['image_path'] = $data['old_image'];
            }

            $menu = $this->Menus->patchEntity($menu, $data);
            $menu->status = 2;

            if ($this->Menus->save($menu)) {
                return $this->redirect(['controller' => $section, 'action' => 'subSubMenus', $sectionDetails->id]);
            } else {
                $this->Flash->error(__('The Menu could not be saved. Please, try again.'));
            }

        }
        $pageSubTitle = 'Sub Sub Menu';
        $actiontitle = 'SubSubMenu';
        $this->set(compact('parentMenus', 'menu', 'actiontitle', 'pageTitle', 'pageSubTitle'));
    }

    public function pendingSubSubMenu($section = null, $id = null)
    {
        $listings = $this->Menus->findPendingSubSubMenus($id);


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

        $pageSubTitle = 'Sub Sub Menu';
        $actiontitle = 'SubSubMenu';
        $this->set(compact('actiontitle', 'pageSubTitle', 'listings'));
    }

    public function enabledSubSubMenu($section = null, $id = null)
    {
        $listings = $this->Menus->findEnabledSubSubMenus($id);

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

        $pageSubTitle = 'Sub Sub Menu';
        $actiontitle = 'SubSubMenu';
        $this->set(compact('actiontitle', 'pageSubTitle', 'listings'));
    }

    public function disabledSubSubMenu($section = null, $id = null)
    {
        $listings = $this->Menus->findDisabledSubSubMenus($id);

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

        $pageSubTitle = 'Sub Sub Menu';
        $actiontitle = 'SubSubMenu';
        $this->set(compact('actiontitle', 'pageSubTitle', 'listings'));
    }

    public function editedSubSubMenu($section = null, $id = null)
    {
        $listings = $this->Menus->findEditedSubSubMenus($id);

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

        $pageSubTitle = 'Sub Sub Menu';
        $actiontitle = 'SubSubMenu';
        $this->set(compact('actiontitle', 'pageSubTitle', 'listings'));
    }

    // public function updateSubMenu($id = null)
    // {
    //     $this->autoRender = false;

    //     $subMenu = $this->Menus->updateSubMenu($id);

    //     $this->response = $this->response->withStatus(200);
    //     echo json_encode(array($subMenu));
    //     $this->log(json_encode(array($subMenu)), 'debug');
    // }
    public function updateSubMenu($id = null)
    {
        // Disable auto-rendering of views
        $this->autoRender = false;
    
        // Fetch the submenu data using the provided ID
        $subMenu = $this->Menus->updateSubMenu($id);
    
        // Create the JSON response
        $this->response = $this->response
            ->withStatus(200) // Set the HTTP status code
            ->withType('application/json') // Set the content type to JSON
            ->withStringBody(json_encode($subMenu)); // Set the response body
    
        // Return the response object
        return $this->response;
    }
    


    public function editMenu($id = null)
    {
        $menuDetails = [];
        $pageTitle = '';

        // Fetch the submenu by its ID
        $menu = $this->Menus->get($id);


        if ($this->request->is(['post', 'patch', 'put'])) {
            $data = $this->request->getData();
            $image_path = $this->request->getData('image_path');
            $imageSize = $image_path->getSize();


            $data['slug'] = Text::slug(strtolower($data['name']));



            // Check if there is an image and then update the image path
            if ($imageSize > 0) {
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $data['image_path']);

                if (!empty($fileOK['urls'])) {
                    $data['image_path'] = substr(
                        $fileOK['file_path'][0],
                        Configure::read('IMAGE_PRELENGTH'),
                        strlen($fileOK['file_path'][0])
                    );
                }
            } else {
                $data['image_path'] = 'temp';
            }

            $menu = $this->Menus->patchEntity($menu, $data);
            $menu->status = 2;

            if ($this->Menus->save($menu)) {
                $this->Flash->success(__('The Menu has been updated.'));
                return $this->redirect(['controller' => 'Settings', 'action' => 'editedMenu']);
            } else {
                $this->Flash->error(__('The Menu could not be saved. Please, try again.'));
            }
        }

        $pageSubTitle = 'Edit Sub Menu';
        $actiontitle = 'EditSubMenu';
        $this->set(compact('menu', 'actiontitle', 'pageTitle', 'pageSubTitle'));
    }

    public function showOnFooter($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_footer' => 1], ['id' => $id]);
            $this->Flash->success(__('Menu has been removed from the footer.'));
        }

        return $this->redirect($this->referer());
    }

    public function removeFromFooter($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_footer' => 0], ['id' => $id]);
            $this->Flash->success(__('Menu has been removed from the footer.'));
        }

        return $this->redirect($this->referer());
    }

    public function showOnTopNav($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_top' => 1], ['id' => $id]);
            $this->Flash->success(__('Menu has been removed from the footer.'));
        }

        return $this->redirect($this->referer());
    }

    public function removeFromTopNav($id = null)
    {
        if ($id) {
            $this->Menus->updateAll(['show_on_top' => 0], ['id' => $id]);
            $this->Flash->success(__('Menu has been removed from the footer.'));
        }

        return $this->redirect($this->referer());
    }

}
