<?php

namespace App\Controller;

use App\Controller\AppController;
use cake\ORM\TableRegistry;
use Cake\I18n\Time;
use Cake\Event\EventInterface;
use Cake\Core\Configure;
use Cake\Log\Log;
use Cake\Http\Exception\NotFoundException;

/**
 * Items Controller
 *
 * @property \App\Model\Table\ItemsTable $Items and AutoSparePartsTable $AutoSpareParts
 */
class GalleryController extends AppController
{
    // protected $slug = "gallery";

    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('Albums');
        $this->loadModel('Galleries');
        $this->slug = "gallery";
    }

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

    }

    public function isAuthorized($user)
    {
        $action = $this->request->getParam('action');
        return true;
    }

    /**
     * Display all images.
     *
     * @return \Cake\Http\Response|null Renders the view
     */
    public function index()
    {
        $pageTitle = 'All Images';
        $slug = $this->slug;

        try {
            Log::info("Starting index process for slug: $slug");

            // Retrieve the menu based on the slug
            $menu = $this->Menus->find()
                ->where(['slug' => $slug])
                ->firstOrFail();
            Log::info("Menu found: " . json_encode($menu));

            // Retrieve all albums
            $listings = $this->Albums->find()
                ->order(['name' => 'ASC'])
                ->all();

            Log::info("Albums query constructed successfully");

            $this->set(compact('pageTitle', 'listings'));
            Log::info("View variables set successfully");

        } catch (\Exception $e) {
            Log::error('Error retrieving albums: ' . $e->getMessage());
            $this->Flash->error(__('An error occurred while retrieving the albums.'));
            return $this->redirect(['action' => 'index']);
        }
        Log::info("Index process completed for slug: $slug");
    }

    public function add()
    {

        $albums = $this->Albums->find("All")->combine('id', 'name');
        $uploaded = false;
        $pageTitle = 'Upload Image';
        if ($this->request->is(['post'])) {
            $data = $this->request->getData();

            foreach ($data['files'] as $image) {

                if (isset($image)) {

                    $cmsbanners = $this->Galleries->newEmptyEntity();
                    // $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH', '') , $image);
                    $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH', '') . 'gallery/', $image);

                    if (!empty($fileOK['urls'])) {
                        $data['image_path'] = substr($fileOK['file_path'][0], Configure::read('IMAGE_PRELENGTH', '0'), strlen($fileOK['file_path'][0]));
                        $imgName = $image->getClientFilename();
                        $data['name'] = str_replace(['_', '-', ':', '\\', '/', '*'], ' ', $imgName);
                    }
                }

                $cmsbanners = $this->Galleries->patchEntity($cmsbanners, $data);
                $this->Galleries->save($cmsbanners);
                $uploaded = true;
            }

            if ($uploaded) {
                $this->Flash->success(__('Banner Uploaded successfully.'));
                return $this->redirect(['action' => 'pendingListings']);
            } else {
                $this->Flash->error(__('The row could not be save. Try again'));
            }
        }
        //  $menu=$this->Menus->find('All')->where(["slug"=>$this->slug])->first();
        //  debug($this->slug);exit;
        $menu_id = "";
        $this->set(compact('pageTitle','menu_id', 'albums'));

    }


    /**
     * View a specific album and its galleries.
     *
     * @param int|null $id The ID of the album
     * @return \Cake\Http\Response|null Renders the view
     */

    public function view($id = null)
    {
        // Ensure the id is provided and is an integer
        if (!$id || !is_numeric($id)) {
            $this->Flash->error(__('Invalid album ID.'));
            return $this->redirect(['action' => 'index']);
        }

        // Fetch the album with the given id
        $cat = $this->Albums->find()
            ->where(['id' => $id])
            ->first();

        // Check if the album exists
        if (!$cat) {
            $this->Flash->error(__('Album not found.'));
            return $this->redirect(['action' => 'index']);
        }

        $pageTitle = h($cat->name); // Sanitize output

        // Fetch the listings for the given album id
        $listingsQuery = $this->Galleries->find()
            ->where(['album_id' => $id])
            ->order(['id' => 'DESC']);

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

        // Set variables to the view
        $this->set(compact('pageTitle', 'listings'));

        // Use the default template rendering (index.ctp for the view method)
        return $this->render('index');
    }


    /**
     * Change background overlay image.
     *
     * @return \Cake\Http\Response|null Redirects to the overlay image action
     */
    public function overlay()
    {
        $pageTitle = 'Change Bg Overlay Image';

        try {
            // Retrieve the CMS banners with the specific ID
            $cmsGallery = $this->Galleries->get(6);
            if (!$cmsGallery) {
                throw new NotFoundException(__('CMS banner not found.'));
            }

            if ($this->request->is(['post', 'put', 'patch'])) {
                $imageField = 'image1';
                $requestData = $this->request->getData();

                if (isset($requestData[$imageField])) {
                    $imageInfo = !empty($requestData[$imageField]['tmp_name']) ? getimagesize($requestData[$imageField]['tmp_name']) : null;

                    if ($imageInfo) {
                        $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH', '') . '/gallery', $requestData[$imageField]);

                        if (array_key_exists('urls', $fileOK)) {
                            $requestData['image_path'] = substr($fileOK['file_path'][0], Configure::read('IMAGE_PRELENGTH', 0), strlen($fileOK['file_path'][0]));
                        }
                    }
                }

                $requestData['status'] = 99;
                $cmsGallery = $this->Galleries->patchEntity($cmsGallery, $requestData);

                if ($this->Galleries->save($cmsGallery)) {
                    $this->Flash->success(__('Bg Overlay Image changed successfully.'));
                    Log::info('Bg Overlay Image for Gallery ID 6 changed successfully.');
                    return $this->redirect(['controller' => 'Home', 'action' => 'overlay-image']);
                } else {
                    throw new \Exception(__('The row could not be saved. Try again.'));
                }
            }

        } catch (\Exception $e) {
            $this->Flash->error($e->getMessage());
            Log::error('Error updating Bg Overlay Image for Gallery ID 6: ' . $e->getMessage());
        }

        $this->set(compact('pageTitle', 'cmsGallery'));
    }

    /**
     * Display all pending listings with status 0.
     *
     * @return \Cake\Http\Response|null Renders the view
     */
    public function pendingListings()
    {
        $pageTitle = 'Pending Images';

        try {
            // Retrieve the menu using the slug
            $menu = $this->Menus->find('all')->where(['slug' => $this->slug])->first();

            if (!$menu) {
                throw new NotFoundException(__('Menu not found for the given slug.'));
            }

            // Retrieve all pending listings with status 0
            $listings = $this->Galleries->find('all')->where(['status' => 0])->order(['id' => 'DESC']);

            // Paginate the listings
            $listings = $this->paginate($listings);

            // Set the variables to be used in the view
            $this->set(compact('pageTitle', 'listings'));

            // Log successful retrieval of pending listings
            Log::info('Pending listings retrieved successfully for menu slug: ' . $this->slug);
        } catch (\Exception $e) {
            $this->Flash->error(__('An error occurred while retrieving the pending listings.'));
            Log::error('Error retrieving pending listings: ' . $e->getMessage());
        }

    }

    /**
     * Display all image albums.
     *
     * @return \Cake\Http\Response|null Renders the view
     */
    public function allListings()
    {
        $pageTitle = 'All Image Albums';

        try {
            // Retrieve all albums
            $listings = $this->Albums->find()
                ->order(['name' => 'ASC'])
                ->all();

            // Log successful retrieval of all albums
            Log::info('All albums retrieved successfully.');

            // Set the variables to be used in the view
            $this->set(compact('pageTitle', 'listings'));

        } catch (\Exception $e) {
            // Log error and set flash message
            Log::error('Error retrieving all albums: ' . $e->getMessage());
            $this->Flash->error(__('An error occurred while retrieving the albums.'));
        }
    }

    /**
     * Display all enabled image listings with status 1.
     *
     * @return \Cake\Http\Response|null Renders the view
     */
    public function enableListings()
    {
        $pageTitle = 'Enable Images';

        try {
            // Retrieve all enabled listings with status 1
            $listings = $this->Galleries->find('all')->where(['status' => 1])->order(['id' => 'DESC']);

            // Paginate the listings
            $listings = $this->paginate($listings);

            // Set the variables to be used in the view
            $this->set(compact('pageTitle', 'listings'));

            // Log successful retrieval of enabled listings
            Log::info('Enabled listings retrieved successfully.');

        } catch (\Exception $e) {
            // Log error and set flash message
            Log::error('Error retrieving enabled listings: ' . $e->getMessage());
            $this->Flash->error(__('An error occurred while retrieving the enabled listings.'));
        }
    }

    /**
     * Display all disabled image listings with status 99.
     *
     * @return \Cake\Http\Response|null Renders the view
     */
    public function disableListings()
    {
        $pageTitle = 'Disable Images';

        try {
            // Retrieve all disabled listings with status 99
            $listings = $this->Galleries->find('all')->where(['status' => 99])->order(['id' => 'DESC']);

            // Paginate the listings
            $listings = $this->paginate($listings);

            // Set the variables to be used in the view
            $this->set(compact('pageTitle', 'listings'));

            // Log successful retrieval of disabled listings
            Log::info('Disabled listings retrieved successfully.');

        } catch (\Exception $e) {
            // Log error and set flash message
            Log::error('Error retrieving disabled listings: ' . $e->getMessage());
            $this->Flash->error(__('An error occurred while retrieving the disabled listings.'));
        }
    }

    /**
     * Enable a specific image by setting its status to 1.
     *
     * @param int|null $id The ID of the image to enable.
     * @return \Cake\Http\Response|null Redirects to the referring page.
     */
    public function enable($id = null)
    {
        // Disable the layout for this action
        $this->viewBuilder()->setLayout(false);

        try {
            // Retrieve the image record by ID
            $banners = $this->Galleries->get($id);

            // Update the status to 1 (enabled)
            $this->request = $this->request->withData('status', 1);
            $banners = $this->Galleries->patchEntity($banners, $this->request->getData());

            if ($this->Galleries->save($banners)) {
                // Log successful update
                Log::info('Image with ID ' . $id . ' has been enabled.');
                $this->Flash->success(__('Image Enabled'));
            } else {
                // Log save error
                Log::error('Failed to enable image with ID ' . $id . '.');
                $this->Flash->error(__('Error Occurred'));
            }
        } catch (\Exception $e) {
            // Log exception details
            Log::error('Exception occurred while enabling image with ID ' . $id . ': ' . $e->getMessage());
            $this->Flash->error(__('An error occurred while enabling the image.'));
        }

        // Redirect to the referring page
        return $this->redirect($this->referer());
    }

    /**
     * Disable a specific image by setting its status to 99.
     *
     * @param int|null $id The ID of the image to disable.
     * @return \Cake\Http\Response|null Redirects to the referring page.
     */

    public function disable($id = null)
    {
        // Disable the layout for this action
        $this->viewBuilder()->setLayout(false);

        try {
            // Retrieve the image record by ID
            $banners = $this->Galleries->get($id);

            // Update the status to 99 (disabled)
            $this->request = $this->request->withData('status', 99);
            $banners = $this->Galleries->patchEntity($banners, $this->request->getData());

            if ($this->Galleries->save($banners)) {
                // Log successful update
                Log::info('Image with ID ' . $id . ' has been disabled.');
                $this->Flash->success(__('Image Disabled'));
            } else {
                // Log save error
                Log::error('Failed to disable image with ID ' . $id . '.');
                $this->Flash->error(__('Error Occurred'));
            }
        } catch (\Exception $e) {
            // Log exception details
            Log::error('Exception occurred while disabling image with ID ' . $id . ': ' . $e->getMessage());
            $this->Flash->error(__('An error occurred while disabling the image.'));
        }

        // Redirect to the referring page
        return $this->redirect($this->referer());
    }

    public function remove($id = null)
    {
        $this->viewBuilder()->setLayout(false);
        $banners = $this->Galleries->get($id);

        if (file_exists(Configure::read('IMAGE_PREPATH', '') . $banners->image_path)) {
            $this->Galleries->delete($banners);
            unlink(Configure::read('IMAGE_PREPATH', '') . $banners->image_path);
            $this->Flash->success(__('Image Removed'));
        } else {
            $this->Flash->error(__('Error Occurred'));
        }
        return $this->redirect($this->referer());
    }

    public function details($album_id = null)
    {
        $pageTitle = 'All Images';

        // Load the gallery records
        // Lets get all the pictures
        $galleryDetails = $this->Galleries->find('all', [
            'conditions' => [
                'status' => 1,
                'album_id' => $album_id
            ]
        ]);

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

        $this->set(compact('pageTitle', 'galleryDetails'));
    }
}