<?php

namespace App\Helpers\FirstParty\ImageGen;

use Image;

class ImageGen
{
    public static function getMainImage($url, $width, $height)
    {
        $canvas = self::getBaseImage($url, 2.0, $width, $height);

        $canvas = self::setImageTint($canvas, $width, $height);

        return $canvas;
    }

    public static function getOpenGraphImage($url, $width, $height, $title = 'Title', $description = 'Description', $website = 'WWW.FUTUREWALKER.CO')
    {
        $canvas = self::getBaseImage($url, 2.0, $width, $height);

        $canvas = self::setImageTint($canvas, $width, $height);

        $canvas = self::setOgTint($canvas, $width, $height);

        $canvas = self::setOgText($canvas, $title, $description, $website);

        return $canvas;
    }

    private static function setOgText($canvas, $title, $description, $website)
    {
        $bold_font = resource_path('fonts/RobotoCondensed/RobotoCondensed-Bold.ttf');
        $font_color = '#ffffff'; // White color for the text

        // Define font sizes
        $font_size_title = 65; // Size of the title text
        $font_size_description = 28; // Size of the description text
        $font_size_website = 28; // Size of the website text

        // Define positions
        $title_position_y = $canvas->height() - 145; // Position for the title at one-third the height
        $description_position_y = $canvas->height() - 30;
        $website_position_y = $canvas->height() - 30;

        // Title - wrapped to 2 lines if necessary, with ellipsis if there is excess text
        $wrappedTitle = wordwrap($title, 35, "\n", true); // Wrap the title
        $lines = explode("\n", $wrappedTitle); // Split the title into lines

        // Adjust these variables as needed
        $lineHeight = 65; // The height of a line of text, adjust as needed for line spacing
        $titleStartPositionY = $title_position_y; // Starting Y position for the title, adjust if needed

        // Check if there are more than 2 lines after wrapping
        if (count($lines) > 2) {
            $lines = array_slice($lines, 0, 2); // Keep only the first two lines
            $secondLine = &$lines[1]; // Reference to the second line
            // Check if the second line can fit an ellipsis; if not, trim the text
            if (strlen($secondLine) > 32) {
                $secondLine = substr($secondLine, 0, 32).'...'; // Trim and add ellipsis
            } else {
                // Add ellipsis directly if there's enough space
                $secondLine .= '...';
            }
        }

        // Now, render each line individually with adjusted line spacing
        foreach ($lines as $index => $line) {
            $currentLineY = $titleStartPositionY + ($index * $lineHeight);
            $canvas->text($line, 30, $currentLineY, function ($font) use ($bold_font, $font_color, $font_size_title) {
                $font->file($bold_font);
                $font->size($font_size_title);
                $font->color($font_color);
                $font->align('left'); // Align text to the left
                $font->valign('bottom'); // Align text to the top of the current line position
            });
        }

        // Description - justified to the left, below the title
        $canvas->text($description, 30, $description_position_y, function ($font) use ($bold_font, $font_color, $font_size_description) {
            $font->file($bold_font);
            $font->size($font_size_description);
            $font->color($font_color);
            $font->align('left'); // Align text to the left
            $font->valign('bottom'); // Align text to the top (as it is below the title)
        });

        // Website - justified to the right, at the bottom of the image
        $canvas->text($website, $canvas->width() - 30, $website_position_y, function ($font) use ($bold_font, $font_color, $font_size_website) {
            $font->file($bold_font);
            $font->size($font_size_website);
            $font->color($font_color);
            $font->align('right'); // Align text to the right
            $font->valign('bottom'); // Align text to the bottom
        });

        return $canvas;
    }

    private static function setOgTint($canvas, $width, $height)
    {

        $og_tint = Image::make(resource_path('images/tints/caption-bg.png'));

        // Stretch the image to the given width and height
        $og_tint->resize($width, $height);

        $canvas->insert($og_tint, 'top-left', 0, 0);

        return $canvas;
    }

    private static function setImageTint($canvas, $width, $height)
    {
        /// ADD TINT
        // Define the directory path
        $directoryPath = resource_path('images/tints');

        // Search for files starting with 'tint-' and count them
        $tintFilesCount = count(glob($directoryPath.'/tint-*'));

        $tint_image = Image::make(resource_path('images/tints/tint-'.rand(1, $tintFilesCount).'.png'));

        // Stretch the image to the given width and height
        $tint_image->resize($width, $height);

        $canvas->insert($tint_image, 'top-left', 0, 0);

        return $canvas;
    }

    private static function getBaseImage($url, $scale = 1.8, $width = 1007, $height = 567)
    {
        $original_image = Image::make($url);

        // Determine which dimension (width or height) is larger
        if ($original_image->width() > $original_image->height()) {
            // Width is larger, resize by width
            $original_image->resize($width, null, function ($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize(); // Prevent upscaling
            });
        } else {
            // Height is larger or equal, resize by height
            $original_image->resize(null, $height, function ($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize(); // Prevent upscaling
            });
        }

        // Scale the image by 1.5x
        $scaled_width = $original_image->width() * $scale;
        $scaled_height = $original_image->height() * $scale;
        $original_image->resize($scaled_width, $scaled_height);

        // Create an empty canvas
        $canvas = Image::canvas($width, $height);

        // Calculate the position to center the scaled image
        $x = ($canvas->width() - $scaled_width) / 2;
        $y = ($canvas->height() - $scaled_height) / 2;

        // Paste the scaled image onto the canvas at the center position

        $canvas->insert($original_image, 'top-left', (int) $x, (int) $y);

        return $canvas;
    }
}
