<?php

namespace App\Http\Controllers;

use App\Models\ForUser;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\Facades\Log;

use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;

class ImageController extends Controller {
    private $objAuth;
    private $objUser;

    public function __construct() {
        $this->objAuth = new AuthController();
        $this->objUser = new UserController();
    }

    public function getUserWithUploads(Request $r) { // /api/rpc/image/get/userwithuploads
        $valid = $this->objAuth->getPermissions($r->kero_token);

        if ($valid['img_viewimg'] == 1) {
            $cols = $this->objUser->getGroupColours()->toArray();
            $imgs = File::directories('storage/assets/images');

            $res = array();

            foreach($imgs as $img) {
                $usr = basename($img);
                $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

                if ($usr != 0) {
                    $user = $this->objUser->getUser($usr, $r)->toArray();
                    $showName = "";
                    $showCol = "";

                    if ($user[0]->display_name !== '') {
                        $showName = $user[0]->display_name;
                    }
                    else {
                        $showName = $user[0]->username;
                    }

                    if ($user[0]->name_style !== '') {
                        $showCol = $user[0]->name_style;
                    }
                    else {
                        foreach($cols as $cl) {
                            if ($cl->id === $user[0]->perm_id) {
                                if ($user[0]->gender === 1) $showCol = $cl->colour_m;
                                else if ($user[0]->gender === 2) $showCol = $cl->colour_f;
                                else $showCol = $cl->colour_u;
                            }
                        }
                    }
                }
                else {
                    $showName = "";
                    $showCol = "";
                }

                $res[] = array(
                    'id' => basename($img),
                    'avatar' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.($user[0]->avatar != '' ? $user[0]->avatar : '/img/noicon.webp'),
                    'userCol' => $showCol,
                    'userName' => $showName
                );
            }

            return $res;
        }
    }

    public function getAll(Request $r) { // /api/rpc/image/get/all
        $valid = $this->objAuth->getPermissions($r->kero_token);

        if ($valid['img_viewimg'] == 1) {
            $cols = $this->objUser->getGroupColours()->toArray();
            $imgs = File::files('storage/assets/images/*');

            $res = array();

            foreach ($imgs as $img) {
                $usr = preg_split("#/#", $img->getPathname());
                $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

                if ($usr[3] != 0) {
                    $user = $this->objUser->getUser($usr[3], $r)->toArray();
                    $showName = "";
                    $showCol = "";

                    if ($user[0]->display_name !== '') {
                        $showName = $user[0]->display_name;
                    }
                    else {
                        $showName = $user[0]->username;
                    }

                    if ($user[0]->name_style !== '') {
                        $showCol = $user[0]->name_style;
                    }
                    else {
                        foreach($cols as $cl) {
                            if ($cl->id === $user[0]->perm_id) {
                                if ($user[0]->gender === 1) $showCol = $cl->colour_m;
                                else if ($user[0]->gender === 2) $showCol = $cl->colour_f;
                                else $showCol = $cl->colour_u;
                            }
                        }
                    }
                }
                else {
                    $showName = "";
                    $showCol = "";
                }

                $res[] = array(
                    'id' => $usr[3],
                    'avatar' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.($user[0]->avatar != '' ? $user[0]->avatar : '/img/noicon.webp'),
                    'name' => $img->getFilename(),
                    'userCol' => $showCol,
                    'userName' => $showName,
                    'image' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.$img->getPathname()
                );
            }

            return $res;
        }
    }

    public function getOwn(Request $r) { // /api/rpc/image/get/own
        $check = $this->objAuth->checkLegit($r->kero_token);

        if ($check == 0) {
            return 'Err!';
        }
        else {
            $valid = $this->objAuth->getPermissions($r->kero_token);

            if ($valid['img_viewimg'] == 1) {
                $cols = $this->objUser->getGroupColours()->toArray();
                $imgs = File::files('storage/assets/images/'.$check);

                $res = array();

                if ($check == 0) {
                    return 'Err!';
                }
                else {
                    foreach ($imgs as $img) {
                        $usr = preg_split("#/#", $img->getPathname());
                        $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

                        if ($usr[3] == $check) {
                            $user = $this->objUser->getUser($usr[3], $r)->toArray();
                            $showName = "";
                            $showCol = "";

                            if ($user[0]->display_name !== '') {
                                $showName = $user[0]->display_name;
                            }
                            else {
                                $showName = $user[0]->username;
                            }

                            if ($user[0]->name_style !== '') {
                                $showCol = $user[0]->name_style;
                            }
                            else {
                                foreach($cols as $cl) {
                                    if ($cl->id === $user[0]->perm_id) {
                                        if ($user[0]->gender === 1) $showCol = $cl->colour_m;
                                        else if ($user[0]->gender === 2) $showCol = $cl->colour_f;
                                        else $showCol = $cl->colour_u;
                                    }
                                }
                            }
                        }
                        else {
                            $showName = "";
                            $showCol = "";
                        }

                        $res[] = array(
                            'id' => $usr[3],
                            'avatar' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.($user[0]->avatar != '' ? $user[0]->avatar : '/img/noicon.webp'),
                            'name' => $img->getFilename(),
                            'userCol' => $showCol,
                            'userName' => $showName,
                            'image' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.$img->getPathname()
                        );
                    }
                }

                return $res;
            }
            else {
                return 'Permission denied.';
            }
        }
    }

    public function getUser($id, Request $r) { // /api/rpc/image/get/user/id
        $valid = $this->objAuth->getPermissions($r->kero_token);

        if ($valid['img_viewimg'] == 1) {
            $cols = $this->objUser->getGroupColours()->toArray();
            $imgs = File::files('storage/assets/images/'.$id);

            $res = array();

            foreach ($imgs as $img) {
                $usr = preg_split("#/#", $img->getPathname());
                $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

                if ($usr[3] != 0) {
                    $user = $this->objUser->getUser($usr[3], $r)->toArray();
                    $showName = "";
                    $showCol = "";

                    if ($user[0]->display_name !== '') {
                        $showName = $user[0]->display_name;
                    }
                    else {
                        $showName = $user[0]->username;
                    }

                    if ($user[0]->name_style !== '') {
                        $showCol = $user[0]->name_style;
                    }
                    else {
                        foreach($cols as $cl) {
                            if ($cl->id === $user[0]->perm_id) {
                                if ($user[0]->gender === 1) $showCol = $cl->colour_m;
                                else if ($user[0]->gender === 2) $showCol = $cl->colour_f;
                                else $showCol = $cl->colour_u;
                            }
                        }
                    }
                }
                else {
                    $showName = "";
                    $showCol = "";
                }

                $res[] = array(
                    'id' => $id,
                    'avatar' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.($user[0]->avatar != '' ? $user[0]->avatar : '/img/noicon.webp'),
                    'name' => $img->getFilename(),
                    'userCol' => $showCol,
                    'userName' => $showName,
                    'image' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.$img->getPathname()
                );
            }

            return $res;
        }
    }

    public function getOther(Request $r) { // /api/rpc/image/get/other
        $check = $this->objAuth->checkLegit($r->kero_token);

        if ($check == 0) {
            return 'Err!';
        }
        else {
            $valid = $this->objAuth->getPermissions($r->kero_token);

            if ($valid['img_viewimg'] == 1) {
                $cols = $this->objUser->getGroupColours()->toArray();
                $dirs = File::directories('storage/assets/images');

                $res = array();

                if ($check == 0) {
                    return 'Err!';
                }
                else {
                    foreach ($dirs as $dir) {
                        $usr = 0;

                        if (basename($dir) != $check) {
                            $usr = basename($dir);
                            $imgs = File::files('assets/images/'.$usr);

                            foreach ($imgs as $img) {
                                $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

                                if ($usr != $check) {
                                    $user = $this->objUser->getUser($usr, $r)->toArray();
                                    $showName = "";
                                    $showCol = "";

                                    if ($user[0]->display_name !== '') {
                                        $showName = $user[0]->display_name;
                                    }
                                    else {
                                        $showName = $user[0]->username;
                                    }

                                    if ($user[0]->name_style !== '') {
                                        $showCol = $user[0]->name_style;
                                    }
                                    else {
                                        foreach($cols as $cl) {
                                            if ($cl->id === $user[0]->perm_id) {
                                                if ($user[0]->gender === 1) $showCol = $cl->colour_m;
                                                else if ($user[0]->gender === 2) $showCol = $cl->colour_f;
                                                else $showCol = $cl->colour_u;
                                            }
                                        }
                                    }
                                }
                                else {
                                    $showName = "";
                                    $showCol = "";
                                }

                                $res[] = array(
                                    'id' => $usr,
                                    'avatar' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.($user[0]->avatar != '' ? $user[0]->avatar : '/img/noicon.webp'),
                                    'name' => $img->getFilename(),
                                    'userCol' => $showCol,
                                    'userName' => $showName,
                                    'image' => $protocol.'://'.$_SERVER['SERVER_NAME'].'/'.$img->getPathname()
                                );
                            }
                        }
                    }
                }

                return $res;
            }
            else {
                return 'Permission denied.';
            }
        }
    }

    public function viewImage(Request $r) { // /api/rpc/image/view
        $valid = $this->objAuth->getPermissions($r->kero_token);

        if ($valid['img_viewimg'] == 1) {
            $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

            if (!isset($r->id) || !isset($r->name)) {
                return 'Err!';
            }

            return $protocol.'://'.$_SERVER['SERVER_NAME'].'/assets/images/'.$r->id.'/'.$r->name;
        }
        else {
            return 'Permission denied.';
        }
    }

    public function uploadImage(Request $r) { // /api/rpc/image/upload
        $check = $this->objAuth->checkLegit($r->kero_token);

        if ($check == 0) {
            return 'Err!';
        }
        else {
            $valid = $this->objAuth->getPermissions($r->kero_token);

            if ($valid['img_addimg'] == 1) {
                if (isset($r->filename)) {
                    if (!is_dir("assets/images/".$check)) {
                        if (!mkdir("assets/images/".$check, 0755, true)) {
                            return "Could not make folder ".$check."<br />";
                        }
                    }

                    $img_dir = "assets/images/".$check."/";
                    $image = $img_dir . $r->filename;
                    $imageFileType = array(
                        'image/png',
                        'image/jpeg',
                        'image/gif'
                    );

                    if (!in_array($r->filetype, $imageFileType)) {
                       return "Only JPG, PNG, JPEG, and GIF are allowed.";
                    }

                    $fname = 'assets/images/'.$check.'/'.$r->filename;
                    $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $r->thefile));
                    Storage::disk('public')->put($fname, $data);

                    return $r->filename;
                }
            }
            else {
                return 'Permission denied.';
            }
        }
    }

    function is_dir_empty($dir) {
        if (!is_readable($dir)) return NULL;
        return (count(scandir($dir)) == 2);
    }

    public function removeImage(Request $r) { // /api/rpc/image/remove
        $check = $this->objAuth->checkLegit($r->kero_token);

        if ($check == 0) {
            return 'Err!';
        }
        else {
            $valid = $this->objAuth->getPermissions($r->kero_token);

            if ($valid['img_delotherimg'] == 1) {
                if (isset($r->name)) {
                    $fname = 'assets/images/'.$r->id.'/'.$r->name;
                    unlink('storage/'.$fname);
                    if ($this->is_dir_empty('storage/assets/images/'.$r->id)) rmdir('storage/assets/images/'.$r->id);

                    return 'Deleted';
                }
            }
            else {
                if (isset($r->name)) {
                    if ($check == $r->id) {
                        if ($valid['img_delownimg'] == 1) {
                            $fname = 'assets/images/'.$check.'/'.$r->name;
                            unlink('storage/'.$fname);
                            if ($this->is_dir_empty('storage/assets/images/'.$check)) rmdir('storage/assets/images/'.$check);

                            return 'Deleted';
                        }
                        else {
                            return 'Permission denied.';
                        }
                    }
                    else {
                        return 'Permission denied.';
                    }
                }
            }
        }
    }
}
