<?php
 
defined('BASEPATH') or exit('No direct script access allowed');
 
// use PHPImageWorkshop\ImageWorkshop;
 
class Ckeditor extends CI_Controller
{
    /**
     * Upload path.
     *
     * @var string
     */
    private $path = 'assets/uploads/ckeditor/';
 
    /**
     * Index page.
     */
    public function index()
    {
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->view('ckeditor');
    }
 
    /**
     * CKEditor image upload
     *
     * Upload by ImageWorkshop package
     *
     * @return string
     */
    public function image_upload()
    {   
        // $this->load->helper('url');
        // $funcNum = $this->input->get('CKEditorFuncNum');
        // $source = $_FILES['upload']['tmp_name'];
        // $file = $_FILES['upload']['name'];
        // $ext = pathinfo($file, PATHINFO_EXTENSION);
        // $ratio = 1200; // 寬度最大比例
        // $allows = [1, 2, 3]; // GIF, JPEG, PNG
        // $newName = date('YmdHis').rand(1000, 9999); //新檔名
        // $message = '';
        // $url = '';
        
        // var_dump($source);

        // echo $funcNum;
        // echo $url;
        // echo $message;


        // try {
        //     $exif = exif_imagetype($source);
 
        //     if (!$exif) {
        //         throw new Exception('檔案格式錯誤');
        //     }
 
        //     if (!in_array($exif, $allows)) {
        //         throw new Exception('僅允許 gif, jpeg, png');
        //     }
 
        //     $imageInfo = getimagesize($source);
        //     $layer = ImageWorkshop::initFromPath($source);
 
        //     // 若寬度大於比例，縮放置比例
        //     if ($imageInfo[0] > $ratio) {
        //         $layer->resizeInPixel($ratio, null, true);
        //     }
 
        //     $fileName = "{$newName}.{$ext}";
        //     $layer->save($this->path, $fileName);
        //     $url = base_url($this->path.$fileName);
        // } catch (Exception $e) {
        //     $message = $e->getMessage();
        // }

        //added image resize
            // $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/assets/images/uploads/";
            // $config['allowed_types']        = 'gif|jpg|png';
            // $config['max_size']             = 100;
            // $config['max_width']            = 1024;
            // $config['max_height']           = 768;
            // $config["file_name"] = "{$newName}.{$ext}";
            // $this->load->library('upload', $config);

            // $this->upload->do_upload('image');
            // $fInfo = $this->upload->data(); // get all info of uploaded file

            // //for image resize
            // $img_array = array();
            // $img_array['image_library'] = 'gd2';
            // $img_array['maintain_ratio'] = TRUE;
            // $img_array['create_thumb'] = TRUE;
            // //you need this setting to tell the image lib which image to process
            // $img_array['source_image'] = $fInfo['full_path'];
            // $img_array['width'] = 113;
            // $img_array['height'] = 75;

            // $this->image_lib->clear(); // added this line
            // $this->image_lib->initialize($img_array); // added this line
            // // $url="";
            // if (!$this->image_lib->resize())




            //         if ( ! $this->upload->do_upload('userfile'))
            //         {
            //                 $url=$config['upload_path'].$config["file_name"];
            //                 // $error = array('error' => $this->upload->display_errors());
            //                 $message=$this->upload->display_errors();
            //                // $this->load->view('upload_form', $error);
            //         }
            //         else
            //         {
            //                 //$data = array('upload_data' => $this->upload->data());
            //                 $message=$this->upload->data();
            //                 //$this->load->view('upload_success', $data);
            //         }
            // }

        // $this->load->helper(array('form', 'url'));

        //     $file_name = time().'-'.$_FILES["image"]['name'];
            
        //     $config = array(
        //         'upload_path' => "./assets/images/",
        //         'allowed_types' => "gif|jpg|png|jpeg|JPEG|JPG|PNG|GIF",
        //         'overwrite' => TRUE,
        //         'max_size' => "26200",
        //         'max_width' => "650",
        //         'max_height' => "500",
        //         'file_name' => $new_name
        //     );
        //     $this->load->library('upload', $config);
    
            
        //     $data = $this->upload->data();
            
        //     // Create thumnail or resize image
        //     $config2 = array(
        //         'source_image'      => $data['full_path'], //get original image
        //         'new_image'         => $data['file_path'].'thumb', //save as new image //need to create thumbs first
        //         'maintain_ratio'    => true,
        //         'width'             => 150
        //     );
        //     $this->load->library('image_lib'); //load library
        //     $this->image_lib->initialize($config2);
        //     $this->image_lib->resize();
        //     $this->image_lib->clear();




        //end added image resize



        //new image upload script
        // $config['upload_path'] = './uploads/';
        $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/assets/images/uploads/";
        $config['allowed_types'] = 'gif|jpg|jpeg|png';
        $config['overwrite'] = FALSE;
        $this->load->library('upload');
     
     
        $funcNum = $this->input->get('CKEditorFuncNum'); //$_GET['CKEditorFuncNum']
        $this->upload->initialize($config);
             
        if (!$this->upload->do_upload('upload')){ // upload the file, 'upload' is the name of the field from CKEditor
             // failed upload
            $message = "Upload failed on blog manager server.";
            $url = '';
         
        }else{ // success copy to wp server
            // $upload_result = base_url() . 'uploads/'. $this->upload->data()['file_name'];
            $upload_result = base_url() . 'assets/images/uploads/'. $this->upload->data()['file_name'];
            $upload_name = $this->upload->data()['file_name'];
     
            // after finished uploading, it will receive a URL
            // $url = $this->BlogModel->UploadImage($blogID, $upload_result, $upload_name); 
            $url=$upload_result;
     
            $message = 'Upload success!';
        }
        echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";

        //end new image upload script

    
        // $string = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction({$funcNum}, '{$url}', '{$message}');</script>";
 
        // $this->output
        //     ->set_content_type('text/html')
        //     ->set_output($string);
    }
 
    /**
     * CKEditor image upload
     *
     * @return string
     */
    public function file_upload()
    {
        $this->load->helper('url');
        $funcNum = $this->input->get('CKEditorFuncNum');
        $source = $_FILES['upload']['tmp_name'];
        $file = $_FILES['upload']['name'];
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $newName = date('YmdHis').rand(1000, 9999); //新檔名
        $message = '';
        $url = '';
        



        echo $funcNum;
        echo $url;
        echo $message;


        try {
            $fileName = "{$newName}.{$ext}";
            $target = $this->path.$fileName;
 
            if (move_uploaded_file($source, $target)) {
                $url = base_url($target);
            } else {
                $message = '上傳失敗';
            }
        } catch (Exception $e) {
            $message = $e->getMessage();
        }
 
        $string = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction({$funcNum}, '{$url}', '{$message}');</script>";
 
        $this->output
            ->set_content_type('text/html')
            ->set_output($string);
    }
}