<?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;
use Kreait\Firebase;



class ApiController extends AppsController {

    public function initialize() {

        parent::initialize();

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

        $this->response = $this->response->withHeader('Access-Control-Allow-Origin', '*');


    }


    public function login()
    {

        $this->request->allowMethod(['post']);

        // Disable view rendering (no need for .ctp file)
        $this->viewBuilder()->setLayout(false); // Disable layout rendering if you're returning JSON
        $this->response = $this->response->withType('application/json');

        // Example response
        $response = [
            'status' => 'success',
            'message' => 'Login successful'
        ];

        // Set the response data to be serialized as JSON
        $this->set($response);
        $this->set('_serialize', array_keys($response)); // Automatically serialize response
    }

    public function fileupload()
    {
        $this->request->allowMethod(['post']); // Only allow POST requests



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



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

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

        $firebase = (new Factory)
            ->withServiceAccount(Configure::read('firebase.key_file'))
            ->createStorage();

        // Access Firebase storage
        $bucket = $firebase->getBucket();

        // 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

            return $this->response->withType('application/json')
                ->withStringBody(json_encode(['status' => 'success', 'filename' => $filename]));

    }
   
}
