<?php
$title = isset($_GET['title']) ? $_GET['title'] : 'Crawlie SEO Guide';
$title = urldecode($title);

$width = 1200;
$height = 630;

$image = imagecreatetruecolor($width, $height);

// Create a premium dark gradient background
for ($i = 0; $i < $height; $i++) {
    $r = 25 - intval(($i / $height) * 10);
    $g = 20 - intval(($i / $height) * 10);
    $b = 45 + intval(($i / $height) * 30);
    $color = imagecolorallocate($image, $r, $g, $b);
    imageline($image, 0, $i, $width, $i, $color);
}

// Draw a subtle accent line at the top
$accentColor = imagecolorallocate($image, 109, 74, 255); // var(--violet-600)
imagefilledrectangle($image, 0, 0, $width, 8, $accentColor);

$white = imagecolorallocate($image, 255, 255, 255);
$muted = imagecolorallocate($image, 150, 140, 180);

$font = __DIR__ . '/../fonts/open-sans/OpenSans-Bold.ttf';
if (!file_exists($font)) {
    $font = __DIR__ . '/../fonts/open-sans/OpenSans-Regular.ttf';
}

$fontSize = 60;
$brandingSize = 24;

// Word wrap logic
$words = explode(' ', $title);
$lines = [];
$currentLine = '';

foreach ($words as $word) {
    $testLine = $currentLine . $word . ' ';
    $bbox = imagettfbbox($fontSize, 0, $font, $testLine);
    $textWidth = $bbox[2] - $bbox[0];
    
    if ($textWidth > ($width - 160)) { // 80px padding on each side
        $lines[] = trim($currentLine);
        $currentLine = $word . ' ';
    } else {
        $currentLine = $testLine;
    }
}
$lines[] = trim($currentLine);

// Draw the text centered vertically
$totalTextHeight = count($lines) * ($fontSize * 1.5);
$startY = ($height - $totalTextHeight) / 2 + $fontSize;

foreach ($lines as $line) {
    $bbox = imagettfbbox($fontSize, 0, $font, $line);
    $textWidth = $bbox[2] - $bbox[0];
    $x = ($width - $textWidth) / 2;
    imagettftext($image, $fontSize, 0, $x, $startY, $white, $font, $line);
    $startY += $fontSize * 1.5;
}

// Draw branding at the bottom
$branding = "Crawlie — Free SEO Audit & Tools";
$bbox = imagettfbbox($brandingSize, 0, $font, $branding);
$brandingWidth = $bbox[2] - $bbox[0];
$bx = ($width - $brandingWidth) / 2;
imagettftext($image, $brandingSize, 0, $bx, $height - 50, $muted, $font, $branding);

header('Content-Type: image/png');
// Cache the image for 1 year
header('Cache-Control: public, max-age=31536000');
imagepng($image);
imagedestroy($image);
?>
