<?php
/**
 * OG image — preview visual da ordem (1200x630 PNG, WhatsApp-friendly).
 * GD-rendered, cached on disk. Pointed to by ordem.php og:image.
 */
require_once __DIR__ . '/db.php';

define('OG_W', 1200);
define('OG_H', 630);
define('CACHE_DIR', __DIR__ . '/data/og_cache');
define('FONT', '/usr/share/fonts/truetype/lato/Lato-Medium.ttf');
define('FONT_BOLD', '/usr/share/fonts/truetype/lato/Lato-Semibold.ttf');
// ponytail: Lato has no Bold weight installed; Semibold stands in. Use FreeSans Bold if Lato Semibold ever missing.
if (!file_exists(FONT_BOLD)) define('FONT_BOLD', '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf');

$token = $_GET['token'] ?? '';
$order = $token ? getOrderByToken($token) : null;
if (!$order) {
    http_response_code(404);
    die('Ordem não encontrada');
}

// Cache key on order id + total + updated content; busts when any of these change.
$cacheKey = 'og_' . (int)$order['id'] . '_' . md5($order['order_number'] . $order['vehicle_name'] . $order['total'] . $order['created_at']);
$cachePath = CACHE_DIR . '/' . $cacheKey . '.png';

if (file_exists($cachePath)) {
    header('Content-Type: image/png');
    header('Cache-Control: public, max-age=86400');
    readfile($cachePath);
    exit;
}

@mkdir(CACHE_DIR, 0775, true);

$img = imagecreatetruecolor(OG_W, OG_H);
$white = imagecolorallocate($img, 255, 255, 255);
$bgTopR = 15; $bgTopG = 23; $bgTopB = 42;     // slate-900
$bgBotR = 30; $bgBotG = 41; $bgBotB = 59;    // slate-800
$accent = imagecolorallocate($img, 37, 99, 235);  // blue-600
$gray = imagecolorallocate($img, 148, 163, 184);  // slate-400
$green = imagecolorallocate($img, 34, 197, 94);  // emerald-600
$dark = imagecolorallocate($img, 15, 23, 42);
$white = imagecolorallocate($img, 255, 255, 255);

// Vertical gradient header (top 45%)
for ($y = 0; $y < (int)(OG_H * 0.45); $y++) {
    $t = $y / (OG_H * 0.45);
    $r = (int)($bgTopR * (1 - $t) + $bgBotR * $t);
    $g = (int)($bgTopG * (1 - $t) + $bgBotG * $t);
    $b = (int)($bgTopB * (1 - $t) + $bgBotB * $t);
    imagefilledrectangle($img, 0, $y, OG_W, $y, imagecolorallocate($img, $r, $g, $b));
}
// White body
imagefilledrectangle($img, 0, (int)(OG_H * 0.45), OG_W, OG_H, $white);
// Accent line
imagefilledrectangle($img, 60, (int)(OG_H * 0.45), 120, (int)(OG_H * 0.45) + 6, $accent);

// Logo (white-ish, top-left)
$logoOk = false;
$logoSrc = __DIR__ . '/autoflex.webp';
if (file_exists($logoSrc)) {
    $logo = @imagecreatefromwebp($logoSrc);
    if ($logo) {
        $lw = 64; $lh = 64;
        imagecopyresampled($img, $logo, 60, 50, 0, 0, $lw, $lh, imagesx($logo), imagesy($logo));
        imagedestroy($logo);
        $logoOk = true;
    }
}

// App name next to logo
$nameX = $logoOk ? 140 : 60;
imagettftext($img, 26, 0, $nameX, 98, $white, FONT_BOLD, APP_NAME);
imagettftext($img, 13, 0, $nameX, 120, $gray, FONT, 'ORÇAMENTO · PROPOSTA TÉCNICA');

// Ordem number, top-right
$ordNum = '#' . ($order['order_number'] ?: $order['id']);
$ordBox = imagettfbbox(34, 0, FONT_BOLD, $ordNum);
$ordW = $ordBox[2] - $ordBox[0];
imagettftext($img, 34, 0, OG_W - 60 - $ordW, 98, $white, FONT_BOLD, $ordNum);

// Vehicle — big, dark, on white body
$vehicle = $order['vehicle_name'] ?: 'Veículo não informado';
$vehicleLines = wrapTTF($img, 40, FONT_BOLD, $vehicle, OG_W - 120);
$vy = (int)(OG_H * 0.45) + 70;
foreach ($vehicleLines as $line) {
    imagettftext($img, 40, 0, 60, $vy, $dark, FONT_BOLD, $line);
    $vy += 52;
}

// Total — accent block
$yTotal = $vy + 30;
imagettftext($img, 16, 0, 60, $yTotal, $gray, FONT, 'VALOR TOTAL');
$totalStr = 'R$ ' . number_format((float)$order['total'], 2, ',', '.');
imagettftext($img, 56, 0, 60, $yTotal + 60, $dark, FONT_BOLD, $totalStr);

// Breakdown right side
$bx = 700;
imagettftext($img, 14, 0, $bx, $yTotal, $gray, FONT, 'PEÇAS');
$partsStr = 'R$ ' . number_format((float)$order['parts_total'], 2, ',', '.');
imagettftext($img, 24, 0, $bx, $yTotal + 32, $dark, FONT_BOLD, $partsStr);
imagettftext($img, 14, 0, $bx, $yTotal + 70, $gray, FONT, 'MÃO DE OBRA');
$laborStr = 'R$ ' . number_format((float)$order['labor_total'], 2, ',', '.');
imagettftext($img, 24, 0, $bx, $yTotal + 102, $dark, FONT_BOLD, $laborStr);

// Footer bar — green CTA hint
imagefilledrectangle($img, 0, OG_H - 70, OG_W, OG_H, $green);
imagettftext($img, 22, 0, 60, OG_H - 27, $white, FONT_BOLD, 'Toque para ver o orçamento completo');

// App footer text
$footBox = imagettfbbox(16, 0, FONT, APP_CNPJ);
$footW = $footBox[2] - $footBox[0];
imagettftext($img, 16, 0, OG_W - 60 - $footW, OG_H - 28, $white, FONT, APP_CNPJ);

header('Content-Type: image/png');
header('Cache-Control: public, max-age=86400');
imagepng($img, $cachePath, 6);
imagepng($img);
imagedestroy($img);

/** Word-wrap for TTF text to a max width in px. */
function wrapTTF($img, float $size, string $font, string $text, int $maxWidth): array {
    $words = preg_split('/\s+/', trim($text));
    $lines = [];
    $cur = '';
    foreach ($words as $w) {
        $try = $cur === '' ? $w : $cur . ' ' . $w;
        $box = imagettfbbox($size, 0, $font, $try);
        if ($box[2] - $box[0] > $maxWidth && $cur !== '') {
            $lines[] = $cur;
            $cur = $w;
        } else {
            $cur = $try;
        }
    }
    if ($cur !== '') $lines[] = $cur;
    return $lines ?: [''];
}