<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
 

//define('ACCESS_KEY', "AKIAXWSGWKL2LMYZ2XSV");
//define('SECRET_KEY', "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");
//use Aws\Credentials\Credentials;
//use Aws\S3\S3Client;
//use Aws\S3\Exception\S3Exception;

class Galeria_ajax extends Builder_Controller 
{
    function __construct() 
    {
        parent::__construct();
        require APPPATH . 'libraries/vendor/autoload.php';
        /*$this->lang->load('anunciante');
        $this->load->model('dados_model', 'anunciante');*/
        $this->load->model('cad_model');
        
        if(!$this->tank_auth->is_logged_in())
        {
            $json = ['valid' => false,'erro' => 4,'msg' => "Acesso negado!"];
            die();
        }
    }
    
    /* ----------------------------- Métodos da galeria ----------------------------- */
    // Upload das imagens da galeria
    public function do_upload_galery() 
    {
        try {
            
                
                
                //dispara exceção caso não tenha dados enviados
                if (!isset($_FILES['files'])) {
                    die(json_encode(['valid' => false,'erro' => 5,'msg' => 'File not uploaded']));
                    //throw new Exception("File not uploaded", 1);
                }
                
                $id_cadastro = $this->session->id_cadastro;
                $id_imovel = $this->input->post('id_imovel');
                
                $imovel = $this->cad_model->getImovelCad(['id_imovel'=> $id_imovel]);
                if(is_null($imovel))
                    throw new Exception("Acesso negado");
                
                
                $allowed_types = array(
                    'gif',
                    'jpg',
                    'jpeg',
                    'png',
                    'GIF',
                    'JPG',
                    'JPEG',
                    'PNG'
                );
                
                $path_parts = pathinfo($_FILES["files"]["name"][0]);
                $extension = $path_parts['extension'];
                
                if (!in_array($extension, $allowed_types))
                    die(json_encode(['valid' => false,'erro' => 5,'msg' => 'Tipo de arquivo não permitido!']));
                
                //$credentials = new Credentials(ACCESS_KEY, SECRET_KEY);
                //$s3 = new S3Client(['version' => 'latest','region' => 'us-west-2']); //,'credentials' => $credentials
                //$this->load->library('easyphpthumbnail');
                //$tmp_name = $_FILES['files']['tmp_name'][0];
                //$name = str_replace($extension, "", convertAccentsAndSpecialToNormal($_FILES['files']['name'][0]) ).'.'.$extension;
                //$putFull = $this->getPutResize($tmp_name, $name, '', 1920, $id_cadastro, $id_imovel);
                //$resFull = $s3->putObject($putFull);
                //$putMedium = $this->getPutResize($tmp_name, $name, 'medium/', 400, $id_cadastro, $id_imovel);
                //$respMedium = $s3->putObject($putMedium);
                //$putThumbnail = $this->getPutResize($tmp_name, $name, 'thumbnail/', 200, $id_cadastro, $id_imovel);
                //$respThumbnail = $s3->putObject($putThumbnail);
                //$imgUrl = $resFull['ObjectURL'];
                
                $tmp_name = $_FILES['files']['tmp_name'][0];
                $name = str_replace($extension, "", convertAccentsAndSpecialToNormal($_FILES['files']['name'][0]) ).'.'.$extension;
                $upload_path = 'anunciante/' . $id_cadastro .'/anuncios/'.$id_imovel.'/galeria';
                Upload::putObjectResize($tmp_name, $name, 400, $upload_path.'/medium');
                Upload::putObjectResize($tmp_name, $name, 200, $upload_path.'/thumbnail');
                $imgUrl = Upload::putObjectResize($tmp_name, $name, 1920, $upload_path);
                
                $uri = str_replace($name, "", $imgUrl);
                $mediumUrl = $uri.'medium/'.$name;
                $thumbnailUrl = $uri.'thumbnail/'.$name;
                $return = [
                    'deleteType'    => '',
                    'deleteUrl'     => base_url('comdono/ajax/galeria_ajax/deletar?file='.$name),
                    'mediumUrl'     => $mediumUrl,
                    'name'          => $name,
                    'size'          => '',
                    'thumbnailUrl'  => $thumbnailUrl,
                    'type'          => '',
                    'uri'           => $uri,
                    'url'           => $imgUrl,
                ];
                
                echo json_encode(['valid' => true,'file' => $return]);
        
            } catch(Exception $e) {
                echo json_encode(['valid' => false,'erro' => 5,'msg' => $e->getMessage()]);
            }
    }
    
    
/*    $thumb -> Colorreplace          = (array)       // Replace a color in the image array(1,'#FFFFFF','#FF6600',60)
                                                   Array with 4 values
                                                   [0]: Boolean 0=disable 1=enable
                                                   [1]: Color to replace in web format: '#00FF00'
                                                   [2]: Replacement color in web format: '#FF0000'
                                                   [3]: RGB tolerance 0 - 100
$thumb -> Colorize              = (array)       // Merge a color in the image array(1,0,0,125,0)
                                                   Array with 5 values
                                                   [0]: Boolean 0=disable 1=enable
                                                   [1]: Red component 0 - 255
                                                   [2]: Green component 0 - 255
                                                   [3]: Blue component 0 - 255
                                                   [4]: Opacity level 0 - 127
$thumb -> Contrast              = (array)       // Change the contrast of the image array(1,30)
                                                   Array with 2 values
                                                   [0]: Boolean 0=disable 1=enable
                                                   [1]: Contrast -100 to 100*/
    
    
    // Tipo: "thumbnail/",  "medium/", "" 
    /*private function getPutResize($tmp_name, $name, $tipo, $width, $id_cadastro, $id_imovel)
    {
        $resize = new easyphpthumbnail;
        		$resize->Thumblocation = $tmp_name;
        		$resize->Thumbfilename = $name;
        		$resize->Thumbwidth = $width;
        		//TA COLOCANDO UM BG NA IMAGEM
        		//$resize->Watermarkpng = 'themes/comdono/img/logo-mda.png';
                //$resize->Watermarkposition = '50% 50%';
                //$resize->Watermarktransparency = 40;
        		//$resize->Quality = 100;
        		//$resize->Colorreplace  = [0];
        		//$resize->Colorize      = [0];
        		//$resize->Contrast      = [0];
        		
        		
        		$resize->Createthumb($tmp_name, 'file');
                
        return [
            'ACL' => 'public-read',
            'Bucket' => getenv('S3_BUCKET'),
            'Key'    => 'anunciante/' . $id_cadastro .'/anuncios/'.$id_imovel.'/galeria/'.$tipo.$name,
            'SourceFile' => $resize->Thumblocation.$resize->Thumbfilename,
            'ContentDisposition' => 'inline; filename='.$name,
            ];
    }*/
    
    
    private function bk()
    {
        //var_dump($_FILES['files']);
                
                
		
        		$thumb = new easyphpthumbnail;
        		//$thumb->Thumblocation = './modules/anunciante/';
        		$thumb->Thumblocation = $_FILES['files']['tmp_name'][0];
        		$thumb->Thumbfilename = $name;
        		$thumb->Thumbwidth = 300;
        		$thumb->Quality = 60;
        		$thumb->Createthumb($_FILES['files']['tmp_name'][0], 'file');
        		
        		
        		
        		
        		
                //var_dump($thumb);
                //die();
                
                $putThumbnail = [
                    'ACL' => 'public-read',
                    'Bucket' => "comdono",
                    'Key'    => 'anunciante/' . $id_cadastro .'/anuncios/'.$id_imovel.'/galeria/thumbnail/'.$_FILES['files']['name'][0],
                    'SourceFile' => $thumb->Thumblocation.$thumb->Thumbfilename,
                    'ContentDisposition' => 'inline; filename='.$_FILES['files']['tmp_name'][0],
                    ];
                
                $putMedium = [
                    'ACL' => 'public-read',
                    'Bucket' => "comdono",
                    'Key'    => 'anunciante/' . $id_cadastro .'/anuncios/'.$id_imovel.'/galeria/medium/'.$_FILES['files']['name'][0],
                    'SourceFile' => $_FILES['files']['tmp_name'][0],
                    'ContentDisposition' => 'inline; filename='.$_FILES['files']['tmp_name'][0],
                    ];
                
                $putFull = [
                    'ACL' => 'public-read',
                    'Bucket' => "comdono",
                    'Key'    => 'anunciante/' . $id_cadastro .'/anuncios/'.$id_imovel.'/galeria/'.$_FILES['files']['name'][0],
                    'SourceFile' => $thumb->Thumblocation.$name,
                    'ContentDisposition' => 'inline; filename='.$_FILES['files']['tmp_name'][0],
                    ];
    }
    
    
    // Upload das imagens da galeria
    public function do_upload_galery_antigo() 
    {
        if(isset($_FILES['files']) && $_FILES['files'])
        {
            $this->load->helper('uploadgaleria');
            //$dados = $this->cad_model->get_dados();
            $id_cadastro = $this->session->id_cadastro;
            $id_imovel = $this->input->post('id_imovel');
            /*$size = $_FILES["files"]["size"][0]; // tamanho da imagem em bytes
            $max_size = 1048576; //1GB
            if ($size > $max_size) 
            {
                die('Max size exceeded');
            }*/
            $allowed_types = array(
                'gif',
                'jpg',
                'jpeg',
                'png',
                'GIF',
                'JPG',
                'JPEG',
                'PNG'
            );
            $path_parts = pathinfo($_FILES["files"]["name"][0]);
            $extension = $path_parts['extension'];
            if (!in_array($extension, $allowed_types)) 
            {
                die('File not allowed');
            }
            $options = array(
                'upload_dir' => './modules/anunciante/' . $id_cadastro .'/'.$id_imovel.'/galeria/',
                'uri' => 'modules/anunciante/' . $id_cadastro .'/'.$id_imovel.'/galeria/',
                'upload_url' => base_url() . 'modules/anunciante/' . $id_cadastro .'/'.$id_imovel.'/galeria/',
                'max_number_of_files' => 100
            );
            $upload_handler = new uploadgaleria($options);
        }
    }
    
    // Insere nome das imagens no banco
    public function update_galery() 
    {
        $xss_data = $this->security->xss_clean($_POST);
        if ($xss_data === null && empty($xss_data)){
            die('Parâmetros inválidos');
        }
        
        $id_imovel = $this->input->post('id_imovel');
        $imovel = $this->cad_model->getImovelCad(['id_imovel'=> $id_imovel]);
        if(is_null($imovel)){
            echo json_encode(['valid' => false,'erro' => 5,'msg' => "Acesso negado"]);
            die();
        }
        
        
        $post = $this->input->post();
        
        $post['id_img_rel'] = $this->cad_model->update_galeria($post);
        if($post['edit_lancamento']??false){
            foreach( $this->cad_model->getImoveis(['id_imovel_rel'=>$post['id_imovel']]) as $imovel ){
                $post['id_imovel'] = $imovel->id_imovel;
                $this->cad_model->update_galeria($post);
            }
        }
        
        echo json_encode($post);
    }
    
    // ordena as imagens no banco
    public function order_priority() 
    {
        $xss_data = $this->security->xss_clean($_POST);
        if ($xss_data === null && empty($xss_data)) 
        {
            die('Parâmetros inválidos');
        }
        $data = $this->input->post('data');
        
        if(!empty($data))
        {
            foreach ($data as $key=>$img)
            {
                if($img['id'] > 0){
                    $this->cad_model->update_galery_by_id(['id_img'=>$img['id'],'priority'=>$key]);
                    $this->cad_model->update_galery_rel_by_id(['id_img'=>$img['id'],'priority'=>$key]);
                }
            }
        }
    }
    
    // Update do alt da imagem
    public function update_image_galery() 
    {
        $this->load->library('form_validation');
        $xss_data = $this->security->xss_clean($_POST);
        //var_dump($xss_data);break;
        $this->form_validation->set_rules('alt', 'Título', 'required');
        if ($xss_data === null && empty($xss_data)) 
        {
            echo json_encode(array(
                'valid' => false,
                'msg' => lang('text_xss_failed')
            ));
        }
        else if ($this->form_validation->run() === FALSE) 
        {
            echo json_encode(array(
                'valid' => false,
                'msg' => validation_errors()
            ));
        }
        else
        {
            $result = $this->cad_model->update_image_galery($this->input->post());
            if ($result === true) 
            {
                echo json_encode(array(
                    'valid' => true,
                    'msg' => lang('text_update_image_galery_ok')
                ));
            }
        }
    }
    public function main_img_galeria() 
    {
        $xss_data = $this->security->xss_clean($_POST);
        if ($xss_data === null && empty($xss_data)) 
        {
            echo json_encode(array(
                'valid' => false,
                'retorno' => 'Parâmetros inválidos.'
            ));
        }
        else
        {
            $img = $this->input->post('file');
            if ($this->cad_model->update_img_principal_galeria($img)) 
            {
                echo json_encode(array(
                    'valid' => true
                ));
            }
            else
            {
                echo json_encode(array(
                    'valid' => false,
                    'msg' => 'A ação não pode ser concluida'
                ));
            }
        }
    }
    public function update_img_galeria() 
    {
            $data['imagem'] = $this->input->post('imagem');
            $data['descricao'] = $this->input->post('descricao');
            $data['alt'] = $this->input->post('descricao');
            
            if ($this->cad_model->update_image_galery($data)) 
            {
                        echo json_encode(array(
                            'valid' => true,
                            'msg' => 'Dados atualizados com sucesso.',
                            'desc' => $this->input->post('descricao_img') ,
                            'name' => $this->input->post('alt')
                        ));
            }
            else
            {
                echo json_encode(array(
                    'valid' => false,
                    'msg' => 'A ação não pode ser concluida.'
                ));
            }
        
    }
    
    /* ----------------------------- Deletar imagem ----------------------------- */
    
    // Deletar imagem da galeria. Remove do banco e da pasta
    public function deletar()
    {
        //$this->ini_method('galeria');
        
        $this->load->helper('uploadgaleria');
        $userID = $this->session->id_cadastro;
        $file_name = $this->input->get('file');
        $id_cadastro = $this->session->id_cadastro;
        $id_imovel = $this->session->id_imovel;

        
        
        $result = $this->cad_model->delete_galeria($file_name);
        
        if($result)
        {
            $file_path = './modules/anunciante/' . $id_cadastro .'/'.$id_imovel.'/galeria/';
            $thumb_path = './modules/anunciante/' . $id_cadastro .'/'.$id_imovel.'/galeria/thumbnail/';
            $med_path = './modules/anunciante/' . $id_cadastro .'/'.$id_imovel.'/galeria/galeria/medium/';
            
            $file = $file_path.$file_name;
            $thumb = $thumb_path.$file_name;
            $medium = $med_path.$file_name;
    
            if(file_exists($file))
            {
                unlink($file);  
            }
            if(file_exists($thumb))
            {
                unlink($thumb);
            }
            if(file_exists($medium))
            {
                unlink($medium);
            } 
        }
            
        echo json_encode(array(
            'valid' => $result
        )); 
    }
}