<?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 Laminas\Diactoros\UploadedFile;

/**
 * Items Controller
 *
 * @property \App\Model\Table\ItemsTable $Items and AutoSparePartsTable $AutoSpareParts
 */
class FileUploadsController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        // Load the Files model for use in this controller
        $this->loadModel('Files');
    }

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

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

    public function index($slug = null)
    {
        $conditions = [];
        $pageTitle = 'All';

        // Determine the page title and conditions based on the slug parameter
        if ($slug == 'pending') {
            $pageTitle = 'Pending';
            $conditions['Files.status'] = 0;
        } else if ($slug == 'enabled') {
            $pageTitle = 'Enabled';
            $conditions['Files.status'] = 1;
        } else if ($slug == 'disabled') {
            $pageTitle = 'Disabled';
            $conditions['Files.status'] = 99;
        } else if ($slug == 'edited') {
            $pageTitle = 'Edited';
            $conditions['Files.status'] = 2;
        }

        // Query listings based on the conditions and order by date_created descending
        $listings = $this->Files->find('all')->where($conditions)->order(['Files.date_created' => 'DESC']);

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

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

    public function add()
    {
        $pageTitle = 'Add File';
        // Initialize a new Files entity
        $fileupload = $this->Files->newEmptyEntity();

        if ($this->request->is(['post'])) {
            $file_field = 'file1';
            $data = $this->request->getData();
            $file = $this->request->getData($file_field);
            $data['title'] =  $data['title'];
            $data['description'] = $data['description'];
            
            if (isset($file)) {
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $file, null, null, false);

                if (!empty($fileOK['urls'])) {
                    $data['file_path'] = substr(
                        $fileOK['file_path'][0],
                        Configure::read('IMAGE_PRELENGTH'),
                        strlen($fileOK['file_path'][0])
                    );                   
                    $data['file_name'] = $file->getClientFilename();
                    $data['file_type'] = $file->getClientMediaType();
                    $data['file_size'] = $file->getSize();
                }
            }
       
            // Patch the entity with new data
            $fileupload = $this->Files->patchEntity($fileupload, $data);

            // Attempt to save the entity
            try {
                if ($this->Files->save($fileupload)) {
                    $this->Flash->success(__('Files added successfully.'));
                    return $this->redirect(['action' => 'index', 'pending']);
                } else {
                    // Log the error
                    Log::error('Failed to save fileupload entity', ['errors' => $fileupload->getErrors()]);
                    $this->Flash->error(__('The file could not be saved. Try again.'));
                }
            } catch (\Exception $e) {
                // Log the exception
                Log::error('Exception during file save', ['exception' => $e]);
                $this->Flash->error(__('An error occurred while saving the file. Please try again.'));
            }
        }

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

    public function edit($id)
    {
        $fileupload = $this->Files->get($id);
        $pageTitle = 'Edit File';

        if ($this->request->is(['post', 'put', 'patch'])) {
            $file_field = 'file1';
            $valid = true;
            $data = $this->request->getData();
            $file = $this->request->getData($file_field);

            if (isset($data[$file_field])) {
                // Log the file upload attempt
                Log::debug('File upload attempt', ['file_field' => $file_field, 'file' => $file]);
                $fileOK = $this->uploadFiles(Configure::read('IMAGE_PREPATH'), $file, null, null, false);

                if (!empty($fileOK['urls'])) {
                    $data['file_path'] = substr(
                        $fileOK['file_path'][0],
                        Configure::read('IMAGE_PRELENGTH'),
                        strlen($fileOK['file_path'][0])
                    );
                    $data['file_name'] = $file->getClientFilename();
                    $data['file_type'] = $file->getClientMediaType();
                    $data['file_size'] = $file->getSize();
                }
            }

            $data['status']= 2;
            
            $fileupload = $this->Files->patchEntity($fileupload, $data);
            
            if ($this->Files->save($fileupload)) {
                $this->Flash->success(__('Files updated successfully.'));
                return $this->redirect(['action' => 'index', 'edited']);
            } else {
                $this->Flash->error(__('The file could not be updated. Try again'));
            }
        }

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

    public function enable($id = null)
    {
        // Disable layout for this action
        $this->viewBuilder()->disableAutoLayout();

        try {
            // Retrieve the file by ID
            $fileupload = $this->Files->get($id);

            // Log the action
            Log::debug('Enabling file', ['file_id' => $id]);

            // Update status to 1
            $this->request = $this->request->withData('status', 1);

            // Patch the entity with new data
            $fileupload = $this->Files->patchEntity($fileupload, $this->request->getData());

            // Attempt to save the entity
            if ($this->Files->save($fileupload)) {
                $this->Flash->success(__('File enabled successfully.'));
            } else {
                // Log the error
                Log::error('Failed to enable file', ['errors' => $fileupload->getErrors()]);
                $this->Flash->error(__('Error occurred while enabling the file.'));
            }
        } catch (\Exception $e) {
            // Log the exception
            Log::error('Exception in enable action', ['exception' => $e]);
            $this->Flash->error(__('An error occurred. Please try again.'));
        }

        // Redirect back to the referrer page
        return $this->redirect($this->referer());
    }
    public function disable($id = null)
    {
        // Disable layout for this action
        $this->viewBuilder()->disableAutoLayout();

        try {
            // Retrieve the file by ID
            $fileupload = $this->Files->get($id);

            // Log the action
            Log::debug('Disabling file', ['file_id' => $id]);

            // Update status to 99
            $this->request = $this->request->withData('status', 99);

            // Patch the entity with new data
            $fileupload = $this->Files->patchEntity($fileupload, $this->request->getData());

            // Attempt to save the entity
            if ($this->Files->save($fileupload)) {
                $this->Flash->success(__('File disabled successfully.'));
            } else {
                // Log the error
                Log::error('Failed to disable file', ['errors' => $fileupload->getErrors()]);
                $this->Flash->error(__('Error occurred while disabling the file.'));
            }
        } catch (\Exception $e) {
            // Log the exception
            Log::error('Exception in disable action', ['exception' => $e]);
            $this->Flash->error(__('An error occurred. Please try again.'));
        }

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

}
