<?php

// Function to overlay an image and add text below it
function overlayImageWithBoldText($backgroundPath, $overlayPath, $outputPath, $x, $y, $overlayWidth, $overlayHeight, $textX, $textX1, $textY, $name, $regNumber, $fontPath, $fontSize, $textColor, $maxFileSizeKB)
{
    // Load the background image
    $background = imagecreatefromstring(file_get_contents($backgroundPath));

    if (!$background) {
        die('Error loading background image.');
    }

    // Load the overlay image
    $overlay = imagecreatefromstring(file_get_contents($overlayPath));

    if (!$overlay) {
        die('Error loading overlay image.');
    }

    // Resize the overlay image
    $resizedOverlay = imagecreatetruecolor($overlayWidth, $overlayHeight);
    imagesavealpha($resizedOverlay, true);
    $transparent = imagecolorallocatealpha($resizedOverlay, 0, 0, 0, 127);
    imagefill($resizedOverlay, 0, 0, $transparent);
    imagecopyresampled(
        $resizedOverlay,
        $overlay,
        0,
        0,
        0,
        0,
        $overlayWidth,
        $overlayHeight,
        imagesx($overlay),
        imagesy($overlay)
    );

    // Copy the resized overlay onto the background at the specified position
    imagecopy($background, $resizedOverlay, $x, $y, 0, 0, $overlayWidth, $overlayHeight);

    // Define text color
    $color = imagecolorallocate($background, 255, 255, 255);

    // Function to draw bold text
    function drawBoldText($image, $size, $angle, $x, $y, $color, $font, $text)
    {
        $offset = 1; // Offset for bold effect
        for ($i = -$offset; $i <= $offset; $i++) {
            for ($j = -$offset; $j <= $offset; $j++) {
                imagettftext($image, $size, $angle, $x + $i, $y + $j, $color, $font, $text);
            }
        }
    }


    // Add bold and larger name and register number text below the overlay
    drawBoldText($background, $fontSize, 0, $textX, $textY, $color, $fontPath, $name);
    drawBoldText($background, $fontSize, 0, $textX1, $textY + 150, $color, $fontPath, $regNumber); // Offset for second line

    // Save the resulting image temporarily as JPEG with reduced quality
    $tempOutputPath = 'temp_output.jpg';
    imagejpeg($background, $tempOutputPath, 75);  // Quality set to 75 for better compression

    // Compress the image to ensure it's within the target file size (500 KB)
    compressImageToFileSize($tempOutputPath, $outputPath, $maxFileSizeKB);

    // Free memory
    imagedestroy($background);
    imagedestroy($overlay);
    imagedestroy($resizedOverlay);

    // Set headers and download the image
    header('Content-Type: image/jpeg');
    header('Content-Disposition: attachment; filename="poster.jpg"');
    readfile($outputPath);
    unlink($tempOutputPath); // Delete the temporary file
    unlink($outputPath); // Optional: Delete the final output file after download
}

// Function to compress an image to a target file size
function compressImageToFileSize($inputPath, $outputPath, $maxFileSizeKB)
{
    $compressionQuality = 75; // Initial quality (0-100)
    do {
        // Save the JPEG image with the specified quality
        imagejpeg(imagecreatefromjpeg($inputPath), $outputPath, $compressionQuality);

        // Check the file size
        $fileSizeKB = filesize($outputPath) / 1024;

        // Reduce quality if file size exceeds the limit
        if ($fileSizeKB > $maxFileSizeKB) {
            $compressionQuality -= 5;  // Decrease quality to reduce size
        }
    } while ($fileSizeKB > $maxFileSizeKB && $compressionQuality > 10); // Stop if compression is too low

    // Free memory
    imagedestroy(imagecreatefromjpeg($inputPath));
}

// Text to add
$regNumber = $_GET['regno'] ?? '';
$name      = $_GET['name']  ?? '';
$image     = $_GET['image'] ?? '';

$characterCount = strlen($name);


// File paths (Adjust these paths as needed)
$backgroundPath = '3.png';
$overlayPath    = $image;
$outputPath     = 'poster.jpg';  // Output in JPEG format
$fontPath       = 'Arial.ttf'; // Path to a TrueType font file

// Position where the overlay will be placed
$x = 250; // Horizontal position (pixels from the left)
$y = 1800; // Vertical position (pixels from the top)

// Dimensions for the resized overlay image
$overlayWidth  = 749;  // Reduce width further for better compression
$overlayHeight = 881; // Reduce height further for better compression

// Text settings
$textX  = $x     + 5 ;
$textX1 = $textX + 45;

if ($characterCount <= 10) {
    $textX  = $x + 130 ;
    $textX1 = $x + 15;
}

// Horizontal position for text
$textY     = $y + $overlayHeight + 100; // Vertical position (below the overlay)
$fontSize  = 75;      // Font size
$textColor = [0, 0, 0]; // Text color (black: RGB [0, 0, 0])

// Max file size (in KB)
$maxFileSizeKB = 500;  // Set the file size limit to 500 KB

// Call the function to overlay image and add text
overlayImageWithBoldText($backgroundPath, $overlayPath, $outputPath, $x, $y, $overlayWidth, $overlayHeight, $textX, $textX1, $textY, $name, $regNumber, $fontPath, $fontSize, $textColor, $maxFileSizeKB);

?>


