<?php
namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Log\Log;
use Cake\Network\Exception\InternalErrorException;
use Cake\ORM\TableRegistry;
use Cake\Utility\Text;

/**
 * Upload component
 */
class UploadComponent extends Component
{

    public $max_files = 6;
    public $is_saved  = false;
    public $upload_file;

    public function send($data)
    {
        Log::write('debug', $data);

        if (!empty($data['uploadfile']['name'])) {

            Log::write('debug', 'uploadfile is not empty.');
            $upload_file = $data['uploadfile'];

            if (count($upload_file) > $this->max_files) {
                throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
            }

            // foreach ($upload_file as $file)
            //  {
            Log::write('debug', "dentro do foreach");
            Log::write('debug', $upload_file);

            $filename      = $upload_file['name'];
            $file_tmp_name = $upload_file['tmp_name'];
            $dir           = WWW_ROOT . 'img' . DS . 'uploads';
            $allowed       = array('png', 'jpg', 'jpeg');

            if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
                throw new InternalErrorException("Error Processing Request", 1);
            } elseif (is_uploaded_file($file_tmp_name)) {
                $filename = Text::uuid() . '-' . $filename;
                $group_db = TableRegistry::get('Groups');

                if (isset($data['id'])) {
                    $entity           = $group_db->get($data['id']);
                    $entity->id       = $data['id'];
                    $entity->filename = $filename;
                    $entity->name     = $data['name'];
                } else {
                    $entity           = $group_db->newEntity();
                    $entity->filename = $filename;
                    $entity->name     = $data['name'];
                }

                $group_db->save($entity);

                move_uploaded_file($file_tmp_name, $dir . DS . $filename);
                $this->is_saved = true;
            }
            // }
        } else if (!empty($data['name']) && !empty($data['id'])) {
            Log::write('debug', 'uploadfile is empty and data[name] is not empty.');

            $group_db     = TableRegistry::get('Groups');
            $entity       = $group_db->get($data['id']);
            $entity->name = $data['name'];

            $group_db->save($entity);
            $this->is_saved = true;
        } else if (!empty($data['name'])) {
            $group_db     = TableRegistry::get('Groups');
            $entity       = $group_db->newEntity();
            $entity->name = $data['name'];

            $group_db->save($entity);
            $this->is_saved = true;
        } else {
            Log::write('debug', 'Deu ruim.');
        }

        return $this->is_saved;
    }

    public function sendSign($data)
    {
        Log::write('debug', $data);

        if (!empty($data['uploadfile']['name'])) {

            Log::write('debug', 'uploadfile is not empty.');
            $upload_file = $data['uploadfile'];

            if (count($upload_file) > $this->max_files) {
                throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
            }

            // foreach ($upload_file as $file)
            //  {
            Log::write('debug', "dentro do foreach");
            Log::write('debug', $upload_file);

            $filename      = $upload_file['name'];
            $file_tmp_name = $upload_file['tmp_name'];
            $dir           = WWW_ROOT . 'img' . DS . 'uploads';
            $allowed       = array('png', 'jpg', 'jpeg');

            if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
                throw new InternalErrorException("Error Processing Request", 1);
            } elseif (is_uploaded_file($file_tmp_name)) {
                $filename = Text::uuid() . '-' . $filename;
                $sign_db  = TableRegistry::get('Signs');

                if (isset($data['id'])) {
                    $entity              = $sign_db->get($data['id']);
                    $entity->id          = $data['id'];
                    $entity->filename    = $filename;
                    $entity->description = $data['description'];
                } else {
                    $entity              = $sign_db->newEntity();
                    $entity->filename    = $filename;
                    $entity->description = $data['description'];
                    $entity->unit_id     = $data['unit_id'];
                }

                $sign_db->save($entity);

                move_uploaded_file($file_tmp_name, $dir . DS . $filename);
                $this->is_saved = true;
            }
            // }
        } else if (!empty($data['description']) && !empty($data['id'])) {
            Log::write('debug', 'uploadfile is empty and data[description] is not empty.');

            $sign_db             = TableRegistry::get('Signs');
            $entity              = $sign_db->get($data['id']);
            $entity->description = $data['description'];

            $sign_db->save($entity);
            $this->is_saved = true;
        } else if (!empty($data['description'])) {
            $sign_db             = TableRegistry::get('Signs');
            $entity              = $sign_db->newEntity();
            $entity->description = $data['description'];

            $sign_db->save($entity);
            $this->is_saved = true;
        } else {
            Log::write('debug', 'Deu ruim.');
        }

        return $this->is_saved;
    }

    public function sendMultiple($data, $entityObject)
    {

        if (!empty($data['uploadfile'])) {

            Log::write('debug', 'uploadfile is not empty.');

            Log::write('debug', '$entityObject');
            Log::write('debug', $entityObject);

            $upload_file = $data['uploadfile'];
            Log::write('debug', 'upload_file.');
            Log::write('debug', $upload_file);

            if (count($upload_file) > $this->max_files) {
                throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
            }

            $unitsTable = TableRegistry::get('Units');

            foreach ($upload_file as $key => $file) {
                Log::write('debug', "dentro do foreach");
                Log::write('debug', $key);
                Log::write('debug', $file);

                if (!$file['name']) {
                    $entityObject->filename = 'default.png';
                    continue;
                }

                $filename      = $file['name'];
                $file_tmp_name = $file['tmp_name'];
                $dir           = WWW_ROOT . 'img' . DS . 'uploads';
                $allowed       = array('png', 'jpg', 'jpeg');

                if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
                    //throw new InternalErrorException ("Error Processing Request yo", 1);
                } 
                elseif (is_uploaded_file($file_tmp_name)) {
                    $filename = Text::uuid() . '-' . $filename;

                    if (isset($entityObject->id)) {
                        //$entityObject->id = $data['id'];
                        Log::write('debug', '$entityObject->id');
                        Log::write('debug', $entityObject->id);

                        $entityObject->$key = $filename;
                    }

                    $entityObject->$key = $filename;

                    move_uploaded_file($file_tmp_name, $dir . DS . $filename);
                }
            }
            unset($entityObject->uploadfile);

            Log::write('debug', '$entityObject');
            Log::write('debug', $entityObject);

            if ($unitsTable->save($entityObject)) {
                Log::write('debug', 'Componente -> salvo com sucesso');
                $this->is_saved = true;
            } else {
                Log::write('debug', 'Componente -> não foi salvo com sucesso');
            }

        } else {
            Log::write('debug', 'uploadfile is  empty.');
            Log::write('debug', $data['uploadfile']);

        }

        //     else if ( !empty($data['name']) && !empty($data['id'])  )
        //     {
        //         Log::write('debug', 'uploadfile is empty and data[name] is not empty.');

        //         $group_db = TableRegistry::get('Groups');
        //         $entity = $group_db->get($data['id']);
        //         $entity->name = $data['name'];

        //         $group_db->save($entity);
        //         $this->is_saved = true;
        //     }

        //     else if ( !empty($data['name']) )
        //     {
        //         $group_db = TableRegistry::get('Groups');
        //         $entity = $group_db->newEntity();
        //         $entity->name = $data['name'];

        //         $group_db->save($entity);
        //         $this->is_saved = true;
        //     }

        //     else
        //     {
        //         Log::write('debug', 'Deu ruim.');
        //     }

        return $this->is_saved;

    }
}
