<?php

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

class Fileupload {

    public function formatNupload($file, $type, $i, $aws = TRUE, $uploadPath = 'assets/tmp/') {
        $_FILES['userFile']['name'] = $_FILES[$file]['name'][$i];
        $_FILES['userFile']['type'] = $_FILES[$file]['type'][$i];
        $_FILES['userFile']['tmp_name'] = $_FILES[$file]['tmp_name'][$i];
        $_FILES['userFile']['error'] = $_FILES[$file]['error'][$i];
        $_FILES['userFile']['size'] = $_FILES[$file]['size'][$i];

        return $this->upload_file("userFile", $type, $aws, $uploadPath);
    }

    public function upload_file($file, $uploadPath = '',$name) {  // file: name of the user file, type: type of the file want to upload
        $CI = & get_instance();
        $path = $uploadPath;       
        $config['upload_path'] = $path;
        $config['overwrite'] = TRUE;
        $config['remove_spaces'] = TRUE;      
        $config['file_name'] = $name.'_'.time(); 
       
        $config['allowed_types'] = 'csv';
 
        $CI->load->library('upload');
        $CI->upload->initialize($config);
        if ($_FILES[$file]['size'] > 0) {
            if (!$CI->upload->do_upload($file)) {
                $error = array('error' => $CI->upload->display_errors());               
                $path = false;
            } else {
                $path = $path .'/'. $CI->upload->data()['file_name'];
//                $path = $CI->upload->data()['file_name'];
            }
        } else {
            $path = FALSE;
        }
        return $path;
    }

    /* IT UPLOADS FILE URL TO OUR CDN */

    public function upload_url($path, $uri, $del = FALSE) { // path: local dir location, dir: name of the dir of CDN where to upload
        $file = new SplFileInfo($path);
        $name = time() . rand(100, 999) . '.' . $file->getExtension();
        $uploadPath = "assets/tmp/" . $name;
        $uri = $uri . $name;
        $img = file_get_contents($path);
        $img = file_put_contents($uploadPath, $img);
        $access = 'public-read';
        if ($img) {
            if ($this->awsUpload($uploadPath, $uri, $access, $del)) {
                return $uri;
            } else {
                return FALSE;
            }
        }
        return FALSE;
    }

    public function upload_local_file($path, $dir, $del = FALSE) { // path: local dir location, dir: name of the dir of CDN where to upload
        $file = new SplFileInfo($path);
        $name = time() . rand(100, 999) . '.' . $file->getExtension();

        $uri = $dir . "/" . $name;
        $access = 'public-read';

        if ($this->awsUpload($path, $uri, $access)) {
            unlink($path);
            $path = $uri;
        } else {
            $path = false;
        }
        return $path;
    }

    public function awsUpload($filePath, $uri, $access, $del = FALSE) {
        $CI = & get_instance();
        $CI->load->library('s3');
        $response = $CI->s3->putObject($CI->s3->inputFile($filePath), cdn_bucket(), $uri, $access);
        if ($response):
            if (!empty($del)):
                $uri = $this->getDelURI($del);
                $CI->s3->deleteObject(cdn_bucket(), $uri);
            endif;
        endif;
        return $response;
    }

    // General PHP if needed
    public function upload_file_ajax($file, $type) {       
        if ($_FILES['file']['size'] > 0) {
            $sourcePath = $_FILES['file']['tmp_name'];
            $extPath = $_FILES['file']['name'];
            $ext = pathinfo("assets/media/" . $extPath, PATHINFO_EXTENSION);
            if ($ext == "jpg" || $ext == "jpeg" || $ext == "png" || $ext == "gif") {
                $name = time() . "." . $ext;
                $path = "assets/tmp/" . $name;

                if (move_uploaded_file($sourcePath, $path)) {
                    $access = 'public-read';
                    $uri = "images/" . $name;
                    if ($this->awsUpload($path, $uri, $access)) {
                        //unlink($path);
                        $path = $uri;
                    } else {
                        $path = false;
                    }
                }
            } else {
                return false;
            }
        } else {
            return false;
        }

        return $path;
    }

    public function getDelURI($path) {
        $protocols = array('http://', 'https://');
        $path = str_replace($protocols, "", $path);
        $pos = strpos($path, '/');
        $path = substr($path, $pos + 1, strlen($path));
        return $path;
    }
    public function upload_file_multiple($file, $uploadPath = '', $product = '', $imagType = '', $rand) {  // file: name of the user file, type: type of the file want to upload
        $CI = & get_instance();
        $path = $uploadPath;
        $pId = substr($product, 0, 4);
        $config['upload_path'] = $path;
        $config['overwrite'] = TRUE;
        $config['remove_spaces'] = TRUE;
        $config['file_name'] = @$pId . $rand;

        $config['allowed_types'] = '*';

        $CI->load->library('upload');
        $CI->upload->initialize($config);
        if ($_FILES[$file]['size'] > 0) {
            if (!$CI->upload->do_upload($file)) {
                $error = array('error' => $CI->upload->display_errors());
                $path = false;
            } else {
                $path = "";
                $path = $CI->upload->data()['file_name'];
                if ($imagType > 0) {
                    $imageSize = array();
                    if ($imagType == 1) {
                        $imageName = $pId . "_feature";
                        $imageSize = array(200, 50);
                    }  //Feature image
                    elseif ($imagType == 2) {
                        $imageName = $pId . "_primary";
                        $imageSize = array(500, 350, 66);
                    } //Primary image
                    elseif ($imagType == 3) {
                        $imageName = $pId . "_bestseller";
                        $imageSize = array(66, 50);
                    }  //Bestseller
                    elseif ($imagType == 4) {
                        $imageName = $pId . "_special";
                        $imageSize = array(66, 50);
                    }  //Special
                    elseif ($imagType == 5) {
                        $imageName = $pId . "_gallery";
                        $imageSize = array(500, 350, 66);
                    }  //Gallery image
                    return $resizeImage = $this->thumb($config, $imageSize, true, $path, $imageName);
                }
            }
        } else {
            $path = FALSE;
        }
        return $path;
    }
    function thumb($config, $imageSize, $create_thumb, $fileName, $imageName) {
        $CI = & get_instance();
        $i = 1;
        $j = 0;
        foreach ($imageSize as $tsize) {
            $config['image_library'] = 'gd2';
            $config['source_image'] = $config['upload_path'] . $fileName;
            $config['create_thumb'] = $create_thumb;
            $config['maintain_ratio'] = TRUE;
            $config['width'] = $tsize;
            $config['height'] = $tsize;
            $config['imageNum'] = $i;
            $config['imageName'] = $imageName;

            $CI->load->library('image_lib', $config);
            $CI->image_lib->initialize($config);
            $imgname = $CI->image_lib->resize();
            if (!empty($imgname)) {
                $allIMG['primary_image'] = $fileName;
                if ($tsize == 500 || $tsize == 200) {
                    $allIMG['product_image'] = $imgname;
                }
                if ($tsize == 350) {
                    $allIMG['primary_sub_image'] = $imgname;
                }
                if ($tsize == 66 || $tsize == 50) {
                    $allIMG['thumb_image'] = $imgname;
                }
            }
            $CI->image_lib->clear();
            $i++;
            $j++;
        }
        /*  print_r($allIMG); exit;  */
        // unlink($config['source_image']); 
        return $allIMG;
    }

}
