<?php

namespace app\libraries;

use Exception;

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

class FileUpload
{
    public $path = FCPATH . 'public';

    public function setPath($path)
    {
        $this->path = $path;
        return $this;
    }

    public function get($pathname)
    {
        return $this->path . $pathname;
    }

    public function base64_image($base64, $target)
    {
        $image = base64_decode($base64);
        file_put_contents($target, $image);
    }

    public function fix_image_orientation($target)
    {
        $image_file_type = strtolower(pathinfo($target, PATHINFO_EXTENSION));

        if (function_exists('exif_read_data')) {
            $exif = exif_read_data($target);
            if ($exif && isset($exif['Orientation'])) {
                $orientation = $exif['Orientation'];
                if ($orientation != 1) {

                    $img = imagecreatefromjpeg($target);
                    $deg = 0;
                    switch ($orientation) {
                        case 3:
                            $deg = 180;
                            break;
                        case 6:
                            $deg = 270;
                            break;
                        case 8:
                            $deg = 90;
                            break;
                    }
                    if ($deg) {
                        $img = imagerotate($img, $deg, 0);
                    }
                    // then rewrite the rotated image back to the disk as $target 
                    $this->saveImage($img, $target, $image_file_type);
                } // if there is some rotation necessary
            } // if have the exif orientation info
        } // if 
    }


    public function image($path, $file, $image_new_width = 0, $image_new_height = 0, $format = 'jpg,png,jpeg,gif')
    {
        // $userId = $this->session->userdata('userid');
        // $destination_path = getcwd() . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'promotion' . DIRECTORY_SEPARATOR . $userId;
        $image_path = $this->get($path);

        $image_name = basename($file["name"]);
        $image_source = $file["tmp_name"];
        $image_temp_target = $image_source;
        $image_target = $image_path . '/' . $image_name;

        $image_file_type = strtolower(pathinfo($image_target, PATHINFO_EXTENSION));
        $image_file_info = getimagesize($image_temp_target);

        $uploadOk = 1;
        $msg = '';

        // Check file size
        //        if ($file["size"] > 500000) {
        //            $msg= "Sorry, your file is too large.";
        //            $uploadOk = 0;
        //        }
        // Allow certain file formats
        $formats = explode(',', $format);
        if (!in_array($image_file_type, $formats)) {
            $msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }
        if ($image_file_info !== false) {
            $msg = "File is an image - " . $image_file_info["mime"] . ".";
            $uploadOk = 1;
        } else {
            $msg = "File is not an image.";
            $uploadOk = 0;
        }
        // Check if file already exists
        if (file_exists($image_target)) {
            unlink($image_target);
            // $msg = "Sorry, file already exists.";
            // $uploadOk = 0;
        }
        if (!file_exists($image_path)) {
            $pathSegments = [];
            $segments = explode('/', $path);
            while (count($segments) > 0) {
                $segment = array_shift($segments);
                array_push($pathSegments, $segment);

                $_path = implode('/', $pathSegments);
                if (!file_exists($this->path . $_path)) {
                    mkdir($this->path . $_path, 0777, true);
                }
            }
        }

        if (!$uploadOk) {
            return array('success' => $uploadOk, 'message' => $msg, 'filename' => $image_name, 'pathname' => $path . '/' . $image_name);
        }

        if ($image_new_width && $image_new_height) {
            move_uploaded_file($image_temp_target, $image_target);
            list($image_width, $image_height) = $image_file_info;

            // $image_width  = imagesx($image_temp_target);
            // $image_height = imagesy($image_temp_target);

            // Create a layer
            $cover = imagecreatetruecolor($image_new_width, $image_new_height);
            // set the color of the layer to white
            $white  = imagecolorallocate($cover, 255, 255, 255);
            // fill entire image (quickly)
            imagefilledrectangle($cover, 0, 0, $image_new_width - 1, $image_new_height - 1, $white);

            if ($image_height > $image_width || $image_height == $image_width) {
                $resized_height = $image_new_height;
                $resized_width = floor($image_width * $resized_height / $image_height);
            } else {
                $resized_width = $image_new_width;
                $resized_height = floor($image_height * $resized_width / $image_width);

                if ($resized_height > $image_new_height) {
                    $resized_height = $image_new_height;
                    $resized_width = floor($image_width * $resized_height / $image_height);
                }
            }
            // $resized_width = $image_height / $image_width * $image_new_width;
            // $resized_height = $image_width / $image_height * $image_new_height;

            $resized = imagecreatetruecolor($resized_width, $resized_height);
            $source = $this->createImage($image_target, $image_file_type);
            imagecopyresampled($resized, $source, 0, 0, 0, 0, $resized_width - 1, $resized_height - 1, $image_width, $image_height);

            $dst_x = $dst_y = 0;

            if ($resized_height >= $image_new_height) $dst_y = ($image_new_height - $resized_height) / 2;
            if ($resized_width < $image_new_width) $dst_x = ($image_new_width - $resized_width) / 2;


            imagecopy($cover, $resized, $dst_x, $dst_y, 0, 0, $resized_width - 1, $resized_height - 1);
            $this->saveImage($cover, $image_target, $image_file_type);

            // unlink($image_temp_target);
            // unset($cover);
            unset($resized);
        } else {
            move_uploaded_file($image_temp_target, $image_target);
        }


        //        log_message('debug', 'filename:'.$filename.';path:'.$path);
        return array('success' => $uploadOk, 'message' => $msg, 'filename' => $image_name, 'pathname' => $path . '/' . $image_name);
    }

    protected function createImage($pathname, $format)
    {
        if (in_array($format, ['jpg', 'jpeg'])) {
            return imagecreatefromjpeg($pathname);
        }
        if ($format == 'gif') {
            return imagecreatefromgif($pathname);
        }
        if ($format == 'png') {
            return imagecreatefrompng($pathname);
        }

        throw new Exception(sprintf('Unsupported file format %s in %s', $format, $pathname));
    }

    protected function saveImage($image, $pathname, $format)
    {
        if (in_array($format, ['jpg', 'jpeg'])) {
            return imagejpeg($image, $pathname, 100);
        }
        if ($format == 'gif') {
            return imagegif($image, $pathname);
        }
        if ($format == 'png') {
            return imagepng($image, $pathname, 0);
        }

        throw new Exception(sprintf('Unsupported file format %s in %s', $format, $pathname));
    }
}
