<?php

/*
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 Avatar extends DbConectionMaker
{
    private string $tempDir = 'avatar/temp';
    private string $avatarDir = 'avatar';
    private array $accepted = ['png','jpg','jpeg','gif'];

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

        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Content-Type: text/html; charset=utf-8');

        $task = $_POST['task'] ?? '';
        $userId = (int)($_POST['userid'] ?? 0);

        if ($task === "insert") {
            $this->insertAvatar($userId);
        }

        if ($task === "delete") {
            $this->deleteAvatar($userId);
        }
    }

    /* -------------------------------------------------- */
    /* AVATAR INSERT */
    /* -------------------------------------------------- */

    private function insertAvatar(int $userId): void
    {
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            return;
        }

        $avatarfile = $this->dbObj->sqlGet(
            "SELECT etchat_avatar, etchat_username 
             FROM {$this->_prefix}etchat_user 
             WHERE etchat_user_id = ?",
            [$userId]
        );

        if (!$avatarfile) {
            return;
        }

        $currentAvatar = $avatarfile[0][0];
        $username = $avatarfile[0][1];

        if (!in_array($currentAvatar, ['noavatar.jpg','mod_ohne_pic.png','autodj.jpg'], true)) {

            $delfile = $this->avatarDir . "/" . $currentAvatar;

            if (file_exists($delfile)) {
                unlink($delfile);
            }
        }

        $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));

        if (!in_array($ext, $this->accepted, true)) {
            return;
        }

        $newname = $username . '-' . time() . '.' . $ext;

        move_uploaded_file(
            $_FILES['file']['tmp_name'],
            $this->tempDir . '/' . $newname
        );

        $this->dbObj->sqlSet(
            "UPDATE {$this->_prefix}etchat_user 
             SET etchat_avatar = ? 
             WHERE etchat_user_id = ?",
            [$newname, $userId]
        );

        $this->resizeAvatar($newname);
    }

    /* -------------------------------------------------- */
    /* AVATAR DELETE */
    /* -------------------------------------------------- */

    private function deleteAvatar(int $userId): void
    {
        $avatarfile = $this->dbObj->sqlGet(
            "SELECT etchat_avatar 
             FROM {$this->_prefix}etchat_user 
             WHERE etchat_user_id = ?",
            [$userId]
        );

        if (!$avatarfile) {
            return;
        }

        $currentAvatar = $avatarfile[0][0];

        if (!in_array($currentAvatar, ['noavatar.jpg','mod_ohne_pic.png','autodj.jpg'], true)) {

            $delfile = $this->avatarDir . "/" . $currentAvatar;

            if (file_exists($delfile)) {
                unlink($delfile);
            }

            $this->dbObj->sqlSet(
                "UPDATE {$this->_prefix}etchat_user 
                 SET etchat_avatar = 'noavatar.jpg'
                 WHERE etchat_user_id = ?",
                [$userId]
            );
        }
    }

    /* -------------------------------------------------- */
    /* IMAGE RESIZE */
    /* -------------------------------------------------- */

    private function resizeAvatar(string $filename): void
    {
        $filepath_old = $this->tempDir . '/' . $filename;
        $filepath_new = $this->avatarDir . '/' . $filename;

        $image_dimension = 100;

        $image_attributes = getimagesize($filepath_old);

        if (!$image_attributes) {
            return;
        }

        [$width_old,$height_old,$type] = $image_attributes;

        if ($width_old <= 0 || $height_old <= 0) {
            return;
        }

        $ratio = $width_old / $height_old;

        if ($ratio > 1) {
            $width_new = $image_dimension;
            $height_new = (int)round($image_dimension / $ratio);
        } else {
            $height_new = $image_dimension;
            $width_new = (int)round($image_dimension * $ratio);
        }

        switch ($type) {

            case IMAGETYPE_GIF:

                $image_old = imagecreatefromgif($filepath_old);
                $image_new = imagecreate($width_new,$height_new);

                imagecopyresampled($image_new,$image_old,0,0,0,0,$width_new,$height_new,$width_old,$height_old);

                imagegif($image_new,$filepath_new);

                break;

            case IMAGETYPE_JPEG:

                $image_old = imagecreatefromjpeg($filepath_old);
                $image_new = imagecreatetruecolor($width_new,$height_new);

                imagecopyresampled($image_new,$image_old,0,0,0,0,$width_new,$height_new,$width_old,$height_old);

                imagejpeg($image_new,$filepath_new);

                break;

            case IMAGETYPE_PNG:

                $image_old = imagecreatefrompng($filepath_old);
                $image_new = imagecreatetruecolor($width_new,$height_new);

                imagealphablending($image_new,false);
                imagesavealpha($image_new,true);

                imagecopyresampled($image_new,$image_old,0,0,0,0,$width_new,$height_new,$width_old,$height_old);

                imagepng($image_new,$filepath_new);

                break;

            default:
                return;
        }

        unlink($filepath_old);

        imagedestroy($image_old);
        imagedestroy($image_new);
    }
}