<?php

/*
 * Copyright (c) 2018 Earworks.
 * Codeigniter Project Template Modification
 * Please contact our email for more information :
 * contact@earworks.co.id
 */

defined('BASEPATH') OR exit('No direct script access allowed');
if (!function_exists('do_upload')) {

    function do_upload($input = null, $config = array(), $path = UPLOAD_PATH) {
        Ci::helper('string');
        $data = array();
        $config_default = [
            'upload_path' => realpath($path),
            'allowed_types' => 'gif|jpg|jpeg|png|pdf|docx|doc',
            'max_size' => 20000,
            'file_name' => isset($config['filename']) ? $config['filename'] : random_string('alpha', 8) . '_' . time()
        ];

        if ($config) {
            $config_default = array_merge($config_default, $config);
        }
        $upload = Ci::library('upload');
        $upload->initialize($config_default);
        if (!$upload->do_upload($input)) {
            $data['error'] = $upload->display_errors();
            $data['data'] = null;
        } else {
            $data['error'] = null;
            $data['data'] = $upload->data();
        }
        return $data;
    }

}
if (!function_exists('do_upload2')) {

    function do_upload2($input = null, $idx = 0, $config = array(), $path = UPLOAD_PATH) {
        Ci::helper('string');
        $data = array();
        $config_default = [
            'upload_path' => realpath($path),
            'allowed_types' => 'gif|jpg|jpeg|png|pdf|docx|doc',
            'max_size' => 20000,
            'file_name' => isset($config['filename']) ? $config['filename'] : random_string('alpha', 8) . '_' . time()
        ];

        if ($config) {
            $config_default = array_merge($config_default, $config);
        }
        if (isset($_FILES[$input]) && isset($_FILES[$input]['name'][$idx])) {
            $_FILES['spam']['name'] = $_FILES[$input]['name'][$idx];
            $_FILES['spam']['type'] = $_FILES[$input]['type'][$idx];
            $_FILES['spam']['tmp_name'] = $_FILES[$input]['tmp_name'][$idx];
            $_FILES['spam']['error'] = $_FILES[$input]['error'][$idx];
            $_FILES['spam']['size'] = $_FILES[$input]['size'][$idx];
        }

        $upload = Ci::library('upload');
        $upload->initialize($config_default);
        if (!$upload->do_upload('spam')) {
            $data['error'] = $upload->display_errors();
            $data['data'] = null;
        } else {
            $data['error'] = null;
            $data['data'] = $upload->data();
        }
        return $data;
    }

}
if (!function_exists('do_delete')) {

    function do_delete($filename = null, $path = IMAGES) {
        $CI = & get_instance();
        $CI->load->helper('file');
        $file = $path . DIRECTORY_SEPARATOR . $filename;
        return is_file($file) ? delete_files($file) : false;
    }

}
if (!function_exists('upload_n_crop')) {

    function upload_n_crop($field, $aspect_ratio = false) {
        $CI = & get_instance();
        $file = do_upload($field);
        if (!$file['error']) {
            $file_x = $CI->input->post("{$field}_x");
            $file_y = $CI->input->post("{$field}_y");
            $file_width = $CI->input->post("{$field}_w");
            $file_height = $CI->input->post("{$field}_h");
            $file_bound_width = $CI->input->post("{$field}_boundw");
            $file_bound_height = $CI->input->post("{$field}_boundh");
            if ($file_bound_width > 0 &&
                    $file_bound_height > 0 &&
                    $file_height > 0 &&
                    $file_width > 0) {
                $file_real_x = ($file_x * $file['data']['image_width']) / $file_bound_width;
                $file_real_y = ($file_y * $file['data']['image_height']) / $file_bound_height;
                $file_real_width = ($file_width * $file['data']['image_width']) / $file_bound_width;
                $file_real_height = ($file_height * $file['data']['image_height']) / $file_bound_height;
                $CI->load->library('image_lib');
                $CI->image_lib->initialize([
                    'source_image' => $file['data']['full_path'],
                    'file_permissions' => 0777,
                    'quality' => 100,
                    'width' => ($aspect_ratio === true) ? ceil($file_real_height) : ceil($file_real_width),
                    'height' => ceil($file_real_height),
                    'x_axis' => $file_real_x,
                    'y_axis' => $file_real_y,
                    'maintain_ratio' => $aspect_ratio
                ]);
                if (!$CI->image_lib->crop()) {
                    $this->session->set_flashdata('error', $CI->image_lib->display_errors());
                    return false;
                }
            }
        }
        return $file;
    }

}
if (!function_exists('do_upload_thumb')) {

    function do_upload_thumb($file = null, $config = array(), $path = null, $static = false) {

        $target = $path . $file;
        $width = 500;
        $height = 500;

        if (isset($config['size'])) {
            $size = explode('x', $config['size']);
            $width = $size[0];
            $height = $size[1];
        }

        $new_file = $path . 'thumbs' . DIRECTORY_SEPARATOR . thumb($file, $width . 'x' . $height, $static);
        if (!is_file($target)) {
            return false;
        }
        if (is_file($new_file)) {
            return true;
        }
        $img_size = getimagesize($target);


        $o_width = $img_size[0];
        $o_height = $img_size[1];
        if ($height == 0) {
            $height = round($width * ($o_height / $o_width));
        }
        if ($width == 0) {
            $height = round($height * ($o_width / $o_height));
        }
        $t_ratio = $width / $height;
        if ($t_ratio > $o_width / $o_height) {
            $config['width'] = $width;
            $config['height'] = round($width * ($o_height / $o_width));
            $y_axis = round(($config['height'] / 2) - ($height / 2));
            $x_axis = 0;
        } else {
            $config['width'] = round($height * ($o_width / $o_height));
            $config['height'] = $height;
            $y_axis = 0;
            $x_axis = round(($config['width'] / 2) - ($width / 2));
        }
        $config['image_library'] = 'gd2';
        $config['source_image'] = $target;
        $config['new_image'] = $new_file;
        $config['create_thumb'] = FALSE;
        $config['maintain_ratio'] = true;
        $config['master_dim'] = 'height';
        $config['quality'] = '70';
        $CI = & get_instance();
        $CI->load->library('image_lib');
        $resizer = $CI->image_lib;
        $resizer->clear();
        $resizer->initialize($config);
        $result = $resizer->resize();


        $config['image_library'] = 'gd2';
        $config['source_image'] = $new_file;
        $config['create_thumb'] = false;
        $config['maintain_ratio'] = false;
        $config['width'] = $width;
        $config['height'] = $height;
        $config['y_axis'] = $y_axis;
        $config['x_axis'] = $x_axis;

        $resizer->clear();
        $resizer->initialize($config);
        if ($result) {
            $result = $resizer->crop();
        }
        return ($result) ? true : $resizer->display_errors();
    }

}
if (!function_exists('thumb')) {

    function thumb($filename, $size = null, $static = false) {
        $width = 500;
        $height = 500;
        if ($size) {
            $exploded = explode('x', $size);
            $width = $exploded[0];
            $height = $exploded[1];
        }
        $new_file_name = pathinfo($filename, PATHINFO_FILENAME) . '_' . $width . 'x' . $height . '.' . pathinfo($filename, PATHINFO_EXTENSION);
        $path = ($static === false) ? UPLOAD_PATH : STATIC_PATH;
        $thumb_path = $path . 'thumbs';
        return $new_file_name;
    }

}
if (!function_exists('thumb_url')) {

    function thumb_url($filename, $size = null, $static = false) {
        $width = 500;
        $height = 500;
        if ($size) {
            $exploded = explode('x', $size);
            $width = $exploded[0];
            $height = $exploded[1];
        }
        $query = '';
        if (strpos($filename, '?') !== false) {
            $partial = explode('?', $filename);
            $filename = $partial[0];
            $query = '?' . $partial[1];
        }
        $url = ($static === false) ? 'img/uploads/thumbs/' : 'img/thumbs/';
        $img = base_url($url . thumb($filename, $width . 'x' . $height, $static) . $query);
        $path = ($static === false) ? UPLOAD_PATH : STATIC_PATH;
        if (!is_file($path . $filename)) {
            $img = base_url('images/static/icon.png');
        } elseif (pathinfo($filename, PATHINFO_EXTENSION) != 'webp') {
            if (do_upload_thumb($filename, ['size' => $width . 'x' . $height], $path, $static) !== true) {
                $img = base_url('images/static/icon.png');
            }
        } else {
            $img = base_url('images/static/icon.png');
        }
        return $img;
    }

}