<?php

namespace App\Controller;

use App\Common\Permission;
use App\Controller\AppsController;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\I18n\I18n;
use RingCentral\SDK\SDK;
use App\Helper\commonLogic;
use App\Utility\Common;
use App\Utility\PdfWriter;
use Cake\View\View;
use App\Utility\IdentityIQParse;
use App\Utility\PasswordCreator;
use Cake\Routing\Router;
use App\Utility\EpicvelocityPrint;
use App\Utility\CreditAnalysis;
use HTML5_Parser;



class FilesController extends AppsController {

    public function initialize() {

        parent::initialize();
        $this->loadComponent('RequestHandler'); // Allow JSON request handling

    }


    public function add()
    {
        $this->request->allowMethod(['post']); // Only allow POST requests
        // Check if a file is uploaded
        if (!$this->request->getData('file')) {
            throw new BadRequestException(__('No file uploaded'));
        }

        $file = $this->request->getData('file');

        // Basic file validation (you can add more checks here)
        if ($file->getError() !== UPLOAD_ERR_OK) {
            throw new InternalErrorException(__('File upload failed'));
        }

        // Generate a new filename
        $filename = time() . '-' . $file->getClientFilename();

        // Define the target directory
        $targetPath = WWW_ROOT . 'files' . DS;

        // Ensure the directory exists
        $folder = new Folder($targetPath, true, 0755);

        // Move the file to the target directory
        $file->moveTo($targetPath . $filename);

        // Save the file details in the database (if applicable)
        $fileEntity = $this->Files->newEmptyEntity();
        $fileEntity->filename = $filename;
        $fileEntity->filepath = 'files/' . $filename; // The relative path to the file
        if ($this->Files->save($fileEntity)) {
            return $this->response->withType('application/json')
                ->withStringBody(json_encode(['status' => 'success', 'filename' => $filename]));
        } else {
            throw new InternalErrorException(__('Unable to save file details'));
        }
    }
   
}
