<?php

// Function to overlay an image onto another with resizing at a specified position
function overlayImage($backgroundPath, $overlayPath, $outputPath, $x, $y, $overlayWidth, $overlayHeight)
{
    // 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.');
    }

    // Create a resized version of the overlay
    $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 image onto the background at the specified position
    imagecopy($background, $resizedOverlay, $x, $y, 0, 0, $overlayWidth, $overlayHeight);

    // Save the resulting image to a file
    imagepng($background, $outputPath);

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

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

// File paths (Adjust these paths as needed)
$backgroundPath = '3.png';
$overlayPath    = '../uploads/675d8f9778d66.png';
$outputPath     = 'output.png';

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

// Dimensions for the resized overlay image
$overlayWidth  = 700;  // Width of the overlay image
$overlayHeight = 700; // Height of the overlay image

// Call the function to overlay the image and download it
overlayImage($backgroundPath, $overlayPath, $outputPath, $x, $y, $overlayWidth, $overlayHeight);
