<?php
    require_once('include/functions/image_directory.php');
    
    $_id = isset($_GET['i']) ? intval($_GET['i']) : 0;

    if ($_id)
    {
        $binaries = mysqli_query_logged("SELECT image_id, thumb FROM z_" . binaries_path($_id) . " WHERE image_id = " . sq($_id));
        if ($binaries_row = mysqli_fetch_assoc($binaries))
        {
            if ($_user)
            {
                $handle = imagecreatefromstring($binaries_row['thumb']);
                $user_id = get_user_id($_user);
                $user_prefs = mysqli_fetch_assoc(mysqli_query_logged("SELECT show_name_avatar FROM users_preferences WHERE user_id = '" . $user_id . "'"));
                if ($user_prefs['show_name_avatar'])
                {
                    $font = 'include/fonts/fstop.ttf';
                    $fontsize = 12;
                    $white = imagecolorallocate($handle, 255, 255, 255);
                    $bar = imagecreatefrompng('include/fonts/black_bar.png');
                    imagecopymerge($handle, $bar, 0, 97, 0, 0, 160, 23, 50);
                    $str_width = (floor($fontsize / 4 * 3) * strlen($_user)) + 10;
                    $x = floor((imagesx($handle) / 2) - ($str_width / 2));
                    $y = 115; 
                    imagettftext($handle, $fontsize, 0, $x, $y, $white, $font, $_user);
                }
                header('content-type: image/png');
                header('content-disposition: inline; filename="' . $binaries_row['image_id'] . '.png"');
                imagepng($handle);
            }
            else
            {
                header('content-type: image/png');
                header('content-disposition: inline; filename="' . $binaries_row['image_id'] . '.png"');
                echo $binaries_row['thumb'];
            }
        }
        else
        {
            display_empty_image();
        }
    }
    else
    {
        display_empty_image();
    }

    function display_empty_image()
    {
        $im = imagecreatetruecolor(264, 264);
        imagefill($im, 0, 0, 0);
        $white = imagecolorallocate($im, 255, 255, 255);
        imagefilledrectangle($im, SIDE_PIXELS, SIDE_PIXELS, 200 + SIDE_PIXELS - 1, 200 + SIDE_PIXELS - 1, $white);
        header ("Content-type: image/png");
        header('content-disposition: inline; filename="empty.png"');
        imagepng($im);
    }
?>