<?php

class DXUtil
{
    public static function debug_print_r(mixed $obj, ?int $color = null)
    {
        if ($color == null || $color < 1 || $color > 5) {
            $color = 1;
        }

        $colors = array('#eff6ff', '#dbeafe', '#bfdbfe', '#93c5fd', '#60a5fa');

        $colorCode = $colors[$color];

        echo "<pre style='background-color: {$colorCode}; padding:10px;'>";
        var_export($obj);
        echo '</pre>';
    }

    public static function outputYes(int $size)
    {
        echo "<span style='font-size:{$size}px; color:green;' class='dashicons dashicons-yes-alt'></span>";
    }

    public static function outputNo(int $size)
    {
        echo "<span style='font-size:{$size}px; color:red;' class='dashicons dashicons-dismiss'></span>";
    }

    public static function outputSuccess(string $text)
    {
        echo '<div class="alert alert-success" role="alert">';
        echo $text;
        echo '</div>';
    }

    public static function outputWarning(string $text)
    {
        echo '<div class="alert alert-warning" role="alert">';
        echo $text;
        echo '</div>';
    }

    public static function outputDanger(string $text)
    {
        echo '<div class="alert alert-danger" role="alert">';
        echo $text;
        echo '</div>';
    }

    public static function doesTableExist(string $tablenameNoPrefix)
    {
        global $wpdb;
        $prefixedTablename = $wpdb->prefix . $tablenameNoPrefix;

        $doesTableExist = $wpdb->get_var("SHOW TABLES LIKE '$prefixedTablename'");
        return $doesTableExist != null;
    }


    public static function outputWpNotice(string $msg, string $dxMsgTypeEnum)
    {
?>
        <div class="notice notice-<?php echo $dxMsgTypeEnum ?> is-dismissible">
            <p><?php echo $msg ?></p>
        </div>
<?php
    }

    public static function generate_guid()
    {
        // Generate a random 32-character hex string
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    public static function importImageToMediaLibrary(string $base64Image)
    {
        if ($base64Image == null)
            return null;

        // Decode base64 image
        $image_data = base64_decode($base64Image);

        // Get image information
        $imageInfo = getimagesizefromstring($image_data);
        // -> $imageInfo[2] contains the image type constant
        $imageType = $imageInfo[2];

        $imgType = null;

        if ($imageType == IMAGETYPE_JPEG) {
            $imgType = 'jpeg';
        } elseif ($imageType == IMAGETYPE_PNG) {
            $imgType = 'png';
        } elseif ($imageType == IMAGETYPE_BMP) {
            $imgType = 'bmp';
        } elseif ($imageType == IMAGETYPE_GIF) {
            $imgType = 'gif';
        } elseif ($imageType == IMAGETYPE_WEBP) {
            $imgType = 'webp';
        } elseif ($imageType == IMAGETYPE_ICO) {
            $imgType = 'ico';
        } else {
            throw new Exception("Either corrupt image or unsupported image type. Supported are: jpeg, png, bmp, gif, webp, ico!");
        }

        //generate guid
        $guid = DXUtil::generate_guid();

        // Generate a unique filename for the image
        $uploadDir = wp_upload_dir()['path'];
        $uniqueFileName = "$guid.$imgType";

        // Specify the file path for the new image
        $file_path =  "$uploadDir/$uniqueFileName";

        // Save the image to the specified file path
        file_put_contents($file_path, $image_data);

        // Prepare the attachment data
        $attachment = array(
            'post_title'     => $uniqueFileName,
            'post_content'   => '',
            'post_status'    => 'inherit',
            'post_mime_type' => "image/$imgType"
        );

        // Insert the attachment into the media library
        $attach_id = wp_insert_attachment($attachment, $file_path);

        //add custom meta-data
        update_post_meta($attach_id, 'sha1', sha1($base64Image));

        // Generate metadata for the attachment
        $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
        wp_update_attachment_metadata($attach_id, $attach_data);

        return $attach_id;
    }

    public static function importDocumentToMediaLibrary(string $filename, string $base64Document)
    {
        if ($filename == null || $base64Document == null)
            return null;

        // Decode base64 document
        $docData = base64_decode($base64Document);

        // Generate a unique filename for the image
        $uploadDir = wp_upload_dir()['path'];
        $uniqueFileName = DXUtil::generateUniqueFilenameInUploadDir($filename);

        // Specify the file path for the new image
        $file_path =  "$uploadDir/$uniqueFileName";

        // Save the image to the specified file path
        file_put_contents($file_path, $docData);

        $file_info = wp_check_filetype($filename);
        //we use this for unknown file-types
        $mimeType = 'application/octet-stream';
        if ($file_info['type']) {
            $mimeType = $file_info['type'];
        }

        // Prepare the attachment data
        $attachment = array(
            'post_title'     => $uniqueFileName,
            'post_content'   => '',
            'post_status'    => 'inherit',
            'post_mime_type' => $mimeType
        );

        // Insert the attachment into the media library
        $attach_id = wp_insert_attachment($attachment, $file_path);

        //add custom meta-data
        update_post_meta($attach_id, 'sha1', sha1($base64Document));

        // Generate metadata for the attachment
        $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
        wp_update_attachment_metadata($attach_id, $attach_data);

        return $attach_id;
    }

    private static function generateUniqueFilenameInUploadDir(string $filename)
    {
        $fileInfo = wp_check_filetype($filename);

        $onlyFilename = '';
        $ext = null;

        if ($fileInfo['ext']) {
            $onlyFilename = str_replace("." . $fileInfo['ext'], "", $filename);
            $ext = $fileInfo['ext'];
        } else {
            $onlyFilename = $filename;
        }

        $uploadDir = wp_upload_dir()['path'];
        $i = 2;

        //check as long till there is a combination of filename-1.ext / filename-2.ext / filename-3.ext etc. till there is one free ...
        while (true) {
            if (file_exists("$uploadDir/$filename")) {

                if ($ext == null) {
                    $filename = "$onlyFilename-$i";
                } else {
                    $filename = "$onlyFilename-$i.$ext";
                }
                $i++;
            } else {
                return $filename;
            }
        }
    }

    public static function getAttachmentIdFromPreviouslyUploadedMedia(string $base64Data)
    {
        //beim Uploaden der Bilder/Dokumente wird ein spezielles Meta-Field "sha1" gesetzt, das hier wieder abgefragt wird
        //wenn es ein Bild/Dokument mit dem Meta-Field gibt, kann dieses wiederverwendet werden, ansonsten wird ein
        //neues Bild/Dokument in die Mediathek hochgeladen - das alles verhindert die "Vermüllung der Mediathek"

        $args = array(
            'post_type'      => 'attachment',
            'post_status'    => 'inherit',
            'posts_per_page' => -1,
            'meta_key' => 'sha1',
            'meta_value' => sha1($base64Data),
        );

        $query = new WP_Query($args);

        while ($query->have_posts()) {
            $query->the_post();

            // Get attachment details
            $attachment_id = get_the_ID();
            return $attachment_id;
        }

        return null;
    }

    public static function splitRequestUri(string $uri): array
    {
        // Parse the URL into its components
        $parsed_url = parse_url($uri);

        // Initialize an array to hold the URL parts
        $url_parts = array(
            'scheme'   => isset($parsed_url['scheme']) ? $parsed_url['scheme'] : '',
            'host'     => isset($parsed_url['host']) ? $parsed_url['host'] : '',
            'port'     => isset($parsed_url['port']) ? $parsed_url['port'] : '',
            'user'     => isset($parsed_url['user']) ? $parsed_url['user'] : '',
            'pass'     => isset($parsed_url['pass']) ? $parsed_url['pass'] : '',
            'path'     => isset($parsed_url['path']) ? $parsed_url['path'] : '',
            'path_vars'     => array(),
            'query'    => isset($parsed_url['query']) ? $parsed_url['query'] : '',
            'query_vars'    => array(),
            'fragment' => isset($parsed_url['fragment']) ? $parsed_url['fragment'] : '',
        );

        // Parse the query string into an associative array
        if (!empty($url_parts['query'])) {
            $query_vars = array();
            wp_parse_str($url_parts['query'], $query_vars);
            $url_parts['query_vars'] = $query_vars;
        }

        // Parse the path string into an associative array
        if (!empty($url_parts['path'])) {
            $path_vars = array_values(array_filter(explode('/', $url_parts['path'])));
            $url_parts['path_vars'] = $path_vars;
        }

        return $url_parts;
    }

    public static function getPluginData()
    {
        return get_plugin_data(DANCE_X_PLUGIN_MAIN_FILE);
    }
}
