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

use Coduo\PHPHumanizer\NumberHumanizer;

class FileModel extends CI_Model
{

    function __construct()
    {
        parent::__construct();
    }

    public function uploadFile($original_name, $tmpname, $size, $type)
    {
        $target_dir = "files" . DIRECTORY_SEPARATOR;
        $filetype = pathinfo(basename($original_name), PATHINFO_EXTENSION);
        $target_file = $target_dir . $this->generateName() . '.' . $filetype;
        $name = explode('.' . $filetype, explode(DIRECTORY_SEPARATOR, $target_file)[1])[0];

        if (!move_uploaded_file($tmpname, $target_file)) {
            die('File couldn\'t be uploaded!');
        }

        $this->db->query('INSERT INTO files (name, original_name, type, size, path) VALUES (?, ?, ?, ?, ?)', [$name, $original_name, $type, $size, $target_file]);

        return "/file/open/" . $name;
    }

    public function uploadImage($name, $max_size, $originalname, $max_width) {
        $config['upload_path']          = './files/';
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = $max_size;
        $config['file_name']            = $this->generateName() . "." . pathinfo(basename($originalname), PATHINFO_EXTENSION);

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload($name)) {
            return null;
        } else {
            $data = $this->upload->data();

            // Resize
            $config['image_library'] = 'gd2';
            $config['source_image'] = $data['full_path'];
            $config['maintain_ratio'] = TRUE;
            $config['width'] = $max_width;

            $this->load->library('image_lib', $config);

            $this->image_lib->resize();

            $this->db->query('INSERT INTO files (name, original_name, type, size, path) VALUES (?, ?, ?, ?, ?)', [$data['raw_name'], $originalname, $data['file_type'], $data['file_size'] * 1024, 'files/' . $data['file_name']]);
            return '/f/' . $data['raw_name'];
        }
    }

    public function uploadFileByContent($content, $original_name, $fullType, $fileSize) {
        $target_dir = "files" . DIRECTORY_SEPARATOR;
        $filetype = pathinfo(basename($original_name), PATHINFO_EXTENSION);
        $target_file = $target_dir . $this->generateName() . '.' . $filetype;
        $name = explode('.' . $filetype, explode(DIRECTORY_SEPARATOR, $target_file)[1])[0];

        $fp = fopen($target_file, 'w');
        fwrite($fp, $content);
        fclose($fp);

        $this->db->query('INSERT INTO files (name, original_name, type, size, path) VALUES (?, ?, ?, ?, ?)', [$name, $original_name, $fullType, $fileSize, $target_file]);

        return '/f/' . $name;
    }

    public function generateName()
    {
        return md5(uniqid(rand(), true));
    }

    public function getFileList()
    {
        $unfiltered_result = $this->db->query('SELECT * FROM files')->result_array();
        $result = [];
        foreach ($unfiltered_result as $item) {
            $item['size'] = NumberHumanizer::binarySuffix(intval($item['size']), $_SESSION['site_lang']);
            $result[] = $item;
        }
        return $result;
    }

    public function delete($id) {
        $filePath = $this->db->query('SELECT path FROM files WHERE ID = ? LIMIT 1', [$id])->result_array()[0];
        unlink($filePath['path']);

        $this->db->query('DELETE FROM files WHERE ID = ? LIMIT 1', [$id]);
    }

}