<?php
declare(strict_types=1);

namespace App\Controller;

use App\Controller\AppController;
use cake\ORM\TableRegistry;
use Cake\Utility\Inflector;
use Cake\I18n\Time;
use Cake\Event\EventInterface;
use Cake\Core\Configure;
use Cake\Log\Log;


/**
 * Albums Controller
 *
 * @property \App\Model\Table\AlbumsTable $Albums
 * @method \App\Model\Entity\Album[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class AlbumsController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('Albums');
    }
    public function beforeRender(EventInterface $event)
    {
        parent::beforeRender($event);
    }

    public function isAuthorized($user)
    {
        return true;
    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index($action = null)
    {
        $listings = $this->Albums->find('all');

        $pageTitle = "Album";

        $title = "All Album";

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

        $this->set(compact('pageTitle', 'listings', 'title'));
    }
    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */
    public function add($type = null)
    {
        // Create a new album entity
        $album = $this->Albums->newEmptyEntity();
        $parentData = [];

        if ($this->request->is('post')) {

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


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

                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';
            }
// debug($image_path);
// exit;
            $album = $this->Albums->patchEntity($album, $data);

            // Attempt to save the new album entity
            try {
                if ($this->Albums->save($album)) {
                    $this->Flash->success(__('The album has been saved successfully.'));
                    Log::info('Album added successfully', ['album_id' => $album->id]);
                    return $this->redirect(['controller' => 'Gallery', 'action' => 'albums']);
                } else {
                    $this->Flash->error(__('The album could not be saved. Please, try again.'));
                    Log::warning('Album save failed', ['errors' => $album->getErrors()]);
                }
            } catch (\Exception $e) {
                $this->Flash->error(__('An error occurred while saving the album. Please, try again.'));
                Log::error('Exception occurred while saving album', ['exception' => $e]);
            }

        }

        // Set view variables
        $pageTitle = "Albums";
        $title = "Add album";
        $this->set(compact('album', 'title', 'pageTitle'));
    }

    /**
     * Edit method
     *
     * @param string|null $id Album 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)
    {

        // Retrieve the album entity by ID
        try {
            $album = $this->Albums->get($id);
        } catch (\Exception $e) {
            $this->Flash->error(__('Album not found.'));
            Log::error('Failed to retrieve album', ['album_id' => $id, 'exception' => $e]);
            return $this->redirect(['action' => 'index']);
        }

        $parentData = [];

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

            if (isset($image_path)) {
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $image_path, null, null, false);

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

            $album = $this->Albums->patchEntity($album, $data);

            // Attempt to save the updated album entity
            try {
                if ($this->Albums->save($album)) {
                    $this->Flash->success(__('The album has been updated successfully.'));
                    Log::info('Album updated successfully', ['album_id' => $id]);
                    return $this->redirect(['controller' => 'Gallery', 'action' => 'albums']);
                } else {
                    $this->Flash->error(__('The album could not be updated. Please, try again.'));
                    Log::warning('Album update failed', ['album_id' => $id, 'errors' => $album->getErrors()]);
                }
            } catch (\Exception $e) {
                $this->Flash->error(__('An error occurred while updating the album. Please, try again.'));
                Log::error('Exception occurred while updating album', ['album_id' => $id, 'exception' => $e]);
            }

        }

        $title = 'Edit album';
        $this->set(compact('album', 'title',));
    }
    public function enable($id = null)
    {
        // Check if the ID is provided
        if ($id) {
            try {
                // Attempt to update the album status to 1 (enabled)
                $result = $this->Albums->updateAll(['status' => 1], ['id' => $id]);

                // Check if any row was updated
                if ($result) {
                    $this->Flash->success(__('Album has been enabled successfully.'));
                    Log::info('Album enabled', ['album_id' => $id]);
                } else {
                    $this->Flash->error(__('Unable to enable the album. Please try again.'));
                    Log::warning('Album enable failed, no rows affected', ['album_id' => $id]);
                }
            } catch (\Exception $e) {
                // Handle any exceptions that occur during the update
                $this->Flash->error(__('An error occurred while enabling the album. Please try again.'));
                Log::error('Exception occurred while enabling album', ['album_id' => $id, 'exception' => $e]);
            }
        } else {
            // Handle the case where no ID is provided
            $this->Flash->error(__('Invalid album ID.'));
            Log::warning('Enable album called with no ID');
        }

        // Redirect to the referring page
        return $this->redirect($this->referer());
    }
    public function disable($id = null)
    {
        // Check if the ID is provided
        if ($id) {
            try {
                // Attempt to update the album status to 99 (disabled)
                $result = $this->Albums->updateAll(['status' => 99], ['id' => $id]);

                // Check if any row was updated
                if ($result) {
                    $this->Flash->success(__('Album has been disabled successfully.'));
                    Log::info('Album disabled', ['album_id' => $id]);
                } else {
                    $this->Flash->error(__('Unable to disable the album. Please try again.'));
                    Log::warning('Album disable failed, no rows affected', ['album_id' => $id]);
                }
            } catch (\Exception $e) {
                // Handle any exceptions that occur during the update
                $this->Flash->error(__('An error occurred while disabling the album. Please try again.'));
                Log::error('Exception occurred while disabling album', ['album_id' => $id, 'exception' => $e]);
            }
        } else {
            // Handle the case where no ID is provided
            $this->Flash->error(__('Invalid album ID.'));
            Log::warning('Disable album called with no ID');
        }

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