<?php
declare(strict_types=1);

/*
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.) 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
*/

class AdminImgManager extends DbConectionMaker
{

    private array $icons = [];

    public function __construct()
    {
		
		parent::__construct();
		
		// -------------------------
        // Session starten
        // -------------------------
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
		
		if (empty($_SESSION['etchat_'.$this->_prefix.'csrf_token'])) {
			$_SESSION['etchat_'.$this->_prefix.'csrf_token'] = bin2hex(random_bytes(16));
		}

		$csrfToken = $_SESSION['etchat_'.$this->_prefix.'csrf_token'];
		
		
        $this->initIcons();
		$this->checkAccess();
        $this->handlePost();
		$this->render();
    }

    private function checkAccess(): void
    {
        $allowed = ['admin', 'grafik', 'co_admin'];

        if (!in_array($_SESSION['etchat_'.$this->_prefix.'user_priv'] ?? '', $allowed, true)) {
            header("Location: ../");
            exit;
        }
    }

    private function initIcons(): void
    {
        $this->icons = [
            ["id"=>"grussbox","title"=>"Grussbox Icon","filename"=>"Grussbox.png","path"=>"img/Grussbox.png","default"=>"img_default/Grussbox.png"],
            ["id"=>"userliste","title"=>"Userliste Icon","filename"=>"Userliste.png","path"=>"img/Userliste.png","default"=>"img_default/Userliste.png"],
            ["id"=>"checked","title"=>"Senden Icon","filename"=>"Checked.png","path"=>"img/Checked.png","default"=>"img_default/Checked.png"],
            ["id"=>"smiley_cool","title"=>"Smiley Icon","filename"=>"Smiley_Cool.png","path"=>"img/Smiley_Cool.png","default"=>"img_default/Smiley_Cool.png"],
            ["id"=>"picture","title"=>"Picture Icon","filename"=>"picture.png","path"=>"img/picture.png","default"=>"img_default/picture.png"],
            ["id"=>"video","title"=>"Video Icon","filename"=>"video.png","path"=>"img/video.png","default"=>"img_default/video.png"],
            ["id"=>"colors","title"=>"Colors Icon","filename"=>"Colors.png","path"=>"img/Colors.png","default"=>"img_default/Colors.png"],
            ["id"=>"display","title"=>"Einstellungen Icon","filename"=>"Display.png","path"=>"img/Display.png","default"=>"img_default/Display.png"],
            ["id"=>"wuerfel_gif","title"=>"Würfel GIF Icon","filename"=>"wuerfel.gif","path"=>"img/wuerfel.gif","default"=>"img_default/wuerfel.gif"],
            ["id"=>"redwuerfel","title"=>"Roter Würfel im Chat","filename"=>"redwuerfel.png","path"=>"img/redwuerfel.png","default"=>"img_default/redwuerfel.png"],
            ["id"=>"vollbild","title"=>"Vollbild Icon","filename"=>"Vollbild.png","path"=>"img/Vollbild.png","default"=>"img_default/Vollbild.png"],
            ["id"=>"bild","title"=>"Bild Hochladen Icon","filename"=>"Bild.png","path"=>"img/Bild.png","default"=>"img_default/Bild.png"],
            ["id"=>"gallery","title"=>"Gallery Icon","filename"=>"Gallery.png","path"=>"img/Gallery.png","default"=>"img_default/Gallery.png"],
            ["id"=>"kurz_befehl","title"=>"Befehle Icon","filename"=>"gear.png","path"=>"img/gear.png","default"=>"img_default/gear.png"],
            ["id"=>"delete_big","title"=>"Logout Icon","filename"=>"Delete_big.png","path"=>"img/Delete_big.png","default"=>"img_default/Delete_big.png"],
            ["id"=>"team","title"=>"Team Icon","filename"=>"team.png","path"=>"img/team.png","default"=>"img_default/team.png"],
            ["id"=>"bewerbung","title"=>"Bewerbung Icon","filename"=>"bewerbung.png","path"=>"img/bewerbung.png","default"=>"img_default/bewerbung.png"],
            ["id"=>"sendeplan","title"=>"Sendeplan Icon","filename"=>"sendeplan.gif","path"=>"img/sendeplan.gif","default"=>"img_default/sendeplan.gif"],
            ["id"=>"playlist","title"=>"Playlist Icon","filename"=>"playlist.png","path"=>"img/playlist.png","default"=>"img_default/playlist.png"],
            ["id"=>"admin","title"=>"Admin Icon","filename"=>"admin.png","path"=>"img/admin.png","default"=>"img_default/admin.png"],
            ["id"=>"djbox","title"=>"DJ Box Icon","filename"=>"djbox.png","path"=>"img/djbox.png","default"=>"img_default/djbox.png"],
            ["id"=>"top_list","title"=>"Top List Icon","filename"=>"top_list.png","path"=>"img/top_list.png","default"=>"img_default/top_list.png"],
            ["id"=>"status_online","title"=>"Status Online","filename"=>"status_online.png","path"=>"img/status_online.png","default"=>"img_default/status_online.png"],
            ["id"=>"status_away","title"=>"Status Away","filename"=>"status_away.png","path"=>"img/status_away.png","default"=>"img_default/status_away.png"],
            ["id"=>"status_busy","title"=>"Status Busy","filename"=>"status_busy.png","path"=>"img/status_busy.png","default"=>"img_default/status_busy.png"],
            ["id"=>"status_chatwache","title"=>"Status Chatwache","filename"=>"status_chatwache.png","path"=>"img/status_chatwache.png","default"=>"img_default/status_chatwache.png"],
            ["id"=>"status_chef","title"=>"Status Chef","filename"=>"status_chef.png","path"=>"img/status_chef.png","default"=>"img_default/status_chef.png"],
            ["id"=>"status_grafik","title"=>"Status Grafik","filename"=>"status_grafik.png","path"=>"img/status_grafik.png","default"=>"img_default/status_grafik.png"],
            ["id"=>"status_invisible","title"=>"Status Invisible","filename"=>"status_invisible.png","path"=>"img/status_invisible.png","default"=>"img_default/status_invisible.png"],
            ["id"=>"status_moderator","title"=>"Status Moderator","filename"=>"status_moderator.png","path"=>"img/status_moderator.png","default"=>"img_default/status_moderator.png"],
            ["id"=>"status_onair","title"=>"Status OnAir","filename"=>"status_onair.png","path"=>"img/status_onair.png","default"=>"img_default/status_onair.png"],
            ["id"=>"status_teamleiter","title"=>"Status Teamleiter","filename"=>"status_teamleiter.png","path"=>"img/status_teamleiter.png","default"=>"img_default/status_teamleiter.png"],
            ["id"=>"status_techniker","title"=>"Status Techniker","filename"=>"status_techniker.png","path"=>"img/status_techniker.png","default"=>"img_default/status_techniker.png"],
            ["id"=>"status_telephone","title"=>"Status Telephone","filename"=>"status_telephone.png","path"=>"img/status_telephone.png","default"=>"img_default/status_telephone.png"],
            ["id"=>"status_user","title"=>"Status User","filename"=>"status_user.png","path"=>"img/status_user.png","default"=>"img_default/status_user.png"],
            ["id"=>"homepage","title"=>"Homepage Icon","filename"=>"homepage.png","path"=>"img/menu/homepage.png","default"=>"img_default/homepage.png"],
            ["id"=>"ts","title"=>"TS Icon","filename"=>"teamspeak.png","path"=>"img/menu/teamspeak.png","default"=>"img_default/teamspeak.png"]
        ];
    }

    private function handlePost(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
		
		    // CSRF CHECK
			$sessionToken = $_SESSION['etchat_'.$this->_prefix.'csrf_token'] ?? '';
			$postToken    = $_POST['csrf_token'] ?? '';

			if (!$sessionToken || !$postToken || !hash_equals($sessionToken, $postToken)) {
				exit('Ungültiger CSRF Token!');
			}

        // ICON HANDLING
        if (isset($_POST['id'])) {
            $id = $_POST['id'];

            foreach ($this->icons as $icon) {
                if ($icon['id'] === $id) {

                    if (isset($_POST['reset'])) {
                        if (file_exists($icon['default'])) copy($icon['default'], $icon['path']);
                    }

                    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
                        $tmp = $_FILES['file']['tmp_name'];
                        $uploadedExt = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
                        $defaultExt = strtolower(pathinfo($icon['default'], PATHINFO_EXTENSION));

                        if ($uploadedExt !== $defaultExt) {
                            exit("Ungültiges Dateiformat! Nur .$defaultExt erlaubt.");
                        }

                        if (!move_uploaded_file($tmp, $icon['path'])) exit("Fehler beim Hochladen!");
                        $this->resizeImageAuto($icon['path'], $icon['default'], $icon['path']);
                    }
                }
            }

            header("Location: ./?AdminImgManager");
            exit;
        }

        // RESET ALL
        if (isset($_POST['reset_all'])) {
            foreach ($this->icons as $icon) {
                if (file_exists($icon['default'])) copy($icon['default'], $icon['path']);
            }
            header("Location: ./?AdminImgManager");
            exit;
        }

        // MENÜ
        if (isset($_POST['delete_menu'])) {
            $file = basename($_POST['delete_menu']);
            $path = "img/menu/".$file;
            if (file_exists($path)) unlink($path);
            header("Location: ./?AdminImgManager");
            exit;
        }

        if (isset($_FILES['upload_menu'])) {
            $tmp  = $_FILES['upload_menu']['tmp_name'];
            $name = basename($_FILES['upload_menu']['name']);
            $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            $dest = "img/menu/".$name;

            if (in_array($ext, ['png','jpg','jpeg','gif']) && is_uploaded_file($tmp)) {
                move_uploaded_file($tmp, $dest);
                $defaultFile = "img_default/menu/default.png";
                if (file_exists($defaultFile)) {
                    $this->resizeImageAuto($dest, $defaultFile, $dest);
                }
            }
            header("Location: ./?AdminImgManager");
            exit;
        }

        // IMAGES
        if (isset($_POST['delete_image'])) {
            $file = basename($_POST['delete_image']);
            $path = "img/images/".$file;
            if (file_exists($path)) unlink($path);
            header("Location: ./?AdminImgManager");
            exit;
        }

        if (isset($_FILES['upload_image'])) {
            $tmp  = $_FILES['upload_image']['tmp_name'];
            $name = basename($_FILES['upload_image']['name']);
            $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            $dest = "img/images/".$name;

            if (in_array($ext, ['png','jpg','jpeg','gif']) && is_uploaded_file($tmp)) {
                move_uploaded_file($tmp, $dest);
                $defaultFile = "img_default/images/default.png";
                if (file_exists($defaultFile)) {
                    $this->resizeImageAuto($dest, $defaultFile, $dest);
                }
            }
            header("Location: ./?AdminImgManager");
            exit;
        }

        // BACKGROUND DELETE
        if (isset($_POST['delete_bg'])) {
            $style = $_SESSION['etchat_'.$this->_prefix.'style'] ?? 'style_chat';
            $file = basename($_POST['delete_bg']);
            $path = "styles/" . $style . "/hintergrund/" . $file;

            if (file_exists($path)) unlink($path);

            header("Location: ./?AdminImgManager");
            exit;
        }

        // BACKGROUND UPLOAD
        if (isset($_FILES['upload_bg'])) {
            $style = $_SESSION['etchat_'.$this->_prefix.'style'] ?? 'style_chat';
            $dir = "styles/" . $style . "/hintergrund/";

            if (is_dir($dir)) {
                $tmp  = $_FILES['upload_bg']['tmp_name'];
                $name = basename($_FILES['upload_bg']['name']);
                $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                $dest = $dir . $name;

                if (in_array($ext, ['png','jpg','jpeg','gif']) && is_uploaded_file($tmp)) {
                    move_uploaded_file($tmp, $dest);
                }
            }

            header("Location: ./?AdminImgManager");
            exit;
        }
    }

    private function resizeImageAuto($uploadedFile, $defaultFile, $outputFile)
    {
        $defaultInfo = @getimagesize($defaultFile);
        if (!$defaultInfo) return false;
        list($targetWidth, $targetHeight) = $defaultInfo;

        $uploadInfo = @getimagesize($uploadedFile);
        if (!$uploadInfo) return false;
        $mime = $uploadInfo['mime'];

        if ($mime === 'image/gif' && class_exists('Imagick')) {
            $gif = new Imagick();
            $gif->readImage($uploadedFile);
            $gif = $gif->coalesceImages();

            foreach ($gif as $frame) {
                $frame->thumbnailImage($targetWidth, $targetHeight);
                $frame->setImagePage(0, 0, 0, 0);
            }

            $gif = $gif->deconstructImages();
            $gif->setImageFormat('gif');
            $gif->writeImages($outputFile, true);
            $gif->clear();
            $gif->destroy();

            return true;
        }

        return $this->resizeStaticImage($uploadedFile, $defaultFile, $outputFile);
    }

    private function resizeStaticImage($sourceFile, $defaultFile, $outputFile)
    {
        $defaultSize = @getimagesize($defaultFile);
        if ($defaultSize === false) return false;

        list($targetWidth, $targetHeight) = $defaultSize;
        $info = @getimagesize($sourceFile);
        if ($info === false) return false;

        switch ($info[2]) {
            case IMAGETYPE_JPEG: $src = imagecreatefromjpeg($sourceFile); break;
            case IMAGETYPE_PNG:  $src = imagecreatefrompng($sourceFile); break;
            case IMAGETYPE_GIF:  $src = imagecreatefromgif($sourceFile); break;
            default: return false;
        }

        $dst = imagecreatetruecolor($targetWidth, $targetHeight);

        if ($info[2] == IMAGETYPE_PNG || $info[2] == IMAGETYPE_GIF) {
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
            $transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
            imagefill($dst, 0, 0, $transparent);
        }

        imagecopyresampled(
            $dst, $src,
            0, 0, 0, 0,
            $targetWidth, $targetHeight,
            imagesx($src), imagesy($src)
        );

        imagepng($dst, $outputFile);

        imagedestroy($src);
        imagedestroy($dst);

        return true;
    }

    private function formatBytes($bytes, $precision = 2)
    {
        $units = ['B','KB','MB','GB'];
        $pow = $bytes > 0 ? floor(log($bytes, 1024)) : 0;
        return round($bytes / pow(1024, $pow), $precision) . ' ' . $units[$pow];
    }

    private function render(): void
    {
        $icons = $this->icons;
		$csrfToken = $_SESSION['etchat_'.$this->_prefix.'csrf_token'] ?? '';

        function e($v){ return htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); }

        include __DIR__ . '/../../styles/admin_tpl/indexImgManager.tpl.html';
    }
}