<?php
declare(strict_types=1);

/** WhatsApp / sosyal için önerilen kart boyutu */
const OG_WIDTH = 1200;
const OG_HEIGHT = 630;

/**
 * Ürün paylaşım meta alanları (profesyonel OG + Twitter).
 * Metin / görsel seçenekleri admin → Paylaşım Kartı ayarlarından gelir.
 *
 * @return array{
 *   title:string, description:string, image:string, url:string, type:string,
 *   image_width:int, image_height:int, image_type:string, image_alt:string,
 *   price:string, currency:string, availability:string, brand:string, jsonld:array
 * }
 */
function product_social_meta(array $product): array
{
    $id = (string) ($product['id'] ?? '');
    $title = trim((string) ($product['title'] ?? 'Ürün'));
    $priceNum = (float) ($product['price'] ?? 0);
    $priceLabel = money($priceNum);
    $desc = trim(preg_replace('/\s+/u', ' ', (string) ($product['description'] ?? '')) ?? '');
    $brand = trim((string) ($product['brand'] ?? ''));
    if ($brand === '') {
        $labels = product_card_labels($product);
        $brand = $labels['brand'] !== '' ? $labels['brand'] : site_name();
    }

    $sellerLine = '';
    if (og_share_flag('show_seller')) {
        $sellerRow = function_exists('product_seller') ? product_seller($product) : null;
        $sellerUsername = ltrim(trim((string) ($product['seller_username'] ?? '')), '@');
        if ($sellerUsername === '' && function_exists('seller_username')) {
            $sellerUsername = seller_username(
                is_array($sellerRow) ? $sellerRow : null,
                trim((string) ($product['seller_name'] ?? 'Satıcı'))
            );
        }
        $sellerHandle = $sellerUsername !== '' ? '@' . $sellerUsername : '';
        $sellerRating = (float) ((is_array($sellerRow) ? ($sellerRow['rating'] ?? null) : null) ?? ($product['seller_rating'] ?? 5));
        $sellerReviews = (int) ((is_array($sellerRow) ? ($sellerRow['review_count'] ?? null) : null) ?? ($product['seller_reviews'] ?? 0));
        $starsText = function_exists('seller_stars_text') ? seller_stars_text($sellerRating) : '★★★★★';

        if ($sellerHandle !== '') {
            $sellerLine = $sellerHandle . ' ' . $starsText;
            if ($sellerReviews > 0) {
                $sellerLine .= ' (' . $sellerReviews . ')';
            }
        }
    }

    $ship = '';
    if (og_share_flag('show_shipping') && product_shipping_is_free($product)) {
        $ship = 'Ücretsiz kargo';
    }

    $securePay = '';
    if (og_share_flag('show_secure_pay')) {
        $securePay = og_share_secure_pay_text();
    }

    $descPart = (og_share_flag('show_description') && $desc !== '') ? $desc : '';

    $parts = array_values(array_filter([
        $sellerLine,
        $ship,
        $securePay,
        $descPart,
    ]));
    $description = implode(' · ', $parts);
    if ($description === '' && og_share_flag('show_price') && $priceNum > 0) {
        $description = $priceLabel;
    }
    if ($description === '') {
        $description = site_name();
    }
    if (mb_strlen($description) > 160) {
        $description = mb_substr($description, 0, 157) . '…';
    }

    $ogTitle = $title;
    if (og_share_flag('show_price') && $priceNum > 0) {
        $ogTitle .= ' — ' . $priceLabel;
    }

    $url = product_share_url($id);
    product_og_card_build($product);
    $image = product_og_card_url($product);
    $stock = (int) ($product['stock'] ?? 0);
    $availability = $stock > 0 ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock';

    $jsonld = [
        '@context' => 'https://schema.org',
        '@type' => 'Product',
        'name' => $title,
        'description' => $description,
        'image' => [absolute_url(product_image_url($product))],
        'sku' => $id,
        'brand' => [
            '@type' => 'Brand',
            'name' => $brand,
        ],
        'offers' => [
            '@type' => 'Offer',
            'url' => $url,
            'priceCurrency' => 'TRY',
            'price' => number_format($priceNum, 2, '.', ''),
            'availability' => $availability,
            'itemCondition' => 'https://schema.org/NewCondition',
            'seller' => [
                '@type' => 'Organization',
                'name' => site_name(),
            ],
        ],
    ];

    $color = product_color_meta($product);
    if ($color) {
        $jsonld['color'] = $color['label'];
    }

    return [
        'title' => $ogTitle,
        'description' => $description,
        'image' => $image,
        'url' => $url,
        'type' => 'website',
        'image_width' => OG_WIDTH,
        'image_height' => OG_HEIGHT,
        'image_type' => 'image/jpeg',
        'image_alt' => $title,
        'price' => number_format($priceNum, 2, '.', ''),
        'currency' => 'TRY',
        'availability' => $availability,
        'brand' => $brand,
        'jsonld' => $jsonld,
    ];
}

/**
 * Sosyal botlara sadece OG meta’lı minimal HTML ver (tam sayfa / header / session yok).
 * WhatsApp kartı için en güvenilir yol.
 *
 * @param array<string,mixed> $social product_social_meta() çıktısı
 */
function social_og_respond_and_exit(array $social): void
{
    $title = (string) ($social['title'] ?? 'Ürün');
    $desc = (string) ($social['description'] ?? '');
    $image = (string) ($social['image'] ?? '');
    $url = (string) ($social['url'] ?? '');
    $w = (int) ($social['image_width'] ?? OG_WIDTH);
    $h = (int) ($social['image_height'] ?? OG_HEIGHT);
    $imgType = (string) ($social['image_type'] ?? 'image/jpeg');
    $alt = (string) ($social['image_alt'] ?? $title);
    $price = (string) ($social['price'] ?? '');
    $currency = (string) ($social['currency'] ?? 'TRY');

    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    header('Content-Type: text/html; charset=UTF-8');
    header('Cache-Control: public, max-age=600');
    http_response_code(200);

    echo '<!DOCTYPE html><html lang="tr"><head><meta charset="UTF-8">';
    echo '<title>' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</title>';
    echo '<meta name="description" content="' . htmlspecialchars($desc, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<link rel="canonical" href="' . htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    // site_name yok — kartta ürün adı + açıklama yeterli
    echo '<meta property="og:type" content="website">';
    echo '<meta property="og:title" content="' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta property="og:description" content="' . htmlspecialchars($desc, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta property="og:url" content="' . htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta property="og:locale" content="tr_TR">';
    echo '<meta property="og:image" content="' . htmlspecialchars($image, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta property="og:image:secure_url" content="' . htmlspecialchars($image, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta property="og:image:width" content="' . $w . '">';
    echo '<meta property="og:image:height" content="' . $h . '">';
    echo '<meta property="og:image:type" content="' . htmlspecialchars($imgType, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta property="og:image:alt" content="' . htmlspecialchars($alt, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    if ($price !== '') {
        echo '<meta property="product:price:amount" content="' . htmlspecialchars($price, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
        echo '<meta property="product:price:currency" content="' . htmlspecialchars($currency, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    }
    echo '<meta name="twitter:card" content="summary_large_image">';
    echo '<meta name="twitter:title" content="' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta name="twitter:description" content="' . htmlspecialchars($desc, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '<meta name="twitter:image" content="' . htmlspecialchars($image, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">';
    echo '</head><body><h1>' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</h1>';
    echo '<p>' . htmlspecialchars($desc, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</p>';
    if ($image !== '') {
        echo '<img src="' . htmlspecialchars($image, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '" alt="" width="' . $w . '" height="' . $h . '">';
    }
    echo '</body></html>';
    exit;
}

/** Paylaşım kartı URL’si — varsa statik JPEG (WhatsApp daha güvenilir), yoksa og-image.php. */
function product_og_card_url(array $product): string
{
    $id = preg_replace('/[^a-zA-Z0-9_\-]/', '', (string) ($product['id'] ?? '')) ?? '';
    $ver = substr(md5(product_og_cache_key($product)), 0, 8);
    if ($id !== '') {
        $rel = 'uploads/og/og_' . $id . '_' . $ver . '.jpg';
        if (is_file(BASE_PATH . '/' . $rel)) {
            return absolute_url($rel);
        }
    }
    // İlk istekte üretmek için dinamik uç (sonra statik dosya oluşur)
    return absolute_url('og-image.php?id=' . rawurlencode((string) ($product['id'] ?? '')) . '&v=' . $ver);
}

function product_og_cache_key(array $product): string
{
    $logoPath = site_logo_filesystem_path();
    $logoStamp = ($logoPath !== '' && is_file($logoPath)) ? (string) filemtime($logoPath) : '0';
    $customPath = function_exists('og_share_custom_image_path') ? og_share_custom_image_path() : '';
    $customStamp = ($customPath !== '' && is_file($customPath)) ? (string) filemtime($customPath) : '0';
    $mode = function_exists('og_share_image_mode') ? og_share_image_mode() : 'product_logo';
    $rev = function_exists('og_share_rev') ? (string) og_share_rev() : '1';
    return 'og|' . $mode . '|r' . $rev . '|'
        . ($product['updated_at'] ?? '')
        . '|' . implode(',', product_images($product))
        . '|' . $logoStamp
        . '|' . $customStamp;
}

/** Tüm ürün OG JPEG önbelleğini sil (ayar değişince). */
function product_og_cache_purge_all(): void
{
    $dir = BASE_PATH . '/uploads/og';
    if (!is_dir($dir)) {
        return;
    }
    foreach (glob($dir . '/og_*.jpg') ?: [] as $file) {
        @unlink($file);
    }
}

/** Yüklü site logosu (PNG/JPEG/WebP). SVG GD ile basılamaz. */
function site_logo_filesystem_path(): string
{
    $file = trim(setting('site_logo'));
    if ($file === '') {
        return '';
    }
    $path = BASE_PATH . '/uploads/logo/' . ltrim($file, '/');
    if (!is_file($path)) {
        return '';
    }
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    if (in_array($ext, ['svg', 'svgz'], true)) {
        return '';
    }
    return $path;
}

/**
 * Ürün fotoğrafının köşesine site logosunu yerleştir (kontrast için hafif beyaz zemin).
 */
function og_overlay_site_logo(GdImage $canvas, int $w, int $h): void
{
    $logoPath = site_logo_filesystem_path();
    if ($logoPath === '') {
        return;
    }
    $logo = og_load_image($logoPath);
    if ($logo === false) {
        return;
    }

    $lw = imagesx($logo);
    $lh = imagesy($logo);
    if ($lw < 1 || $lh < 1) {
        imagedestroy($logo);
        return;
    }

    $maxW = 210;
    $maxH = 78;
    $scale = min($maxW / $lw, $maxH / $lh);
    $nw = (int) max(1, round($lw * $scale));
    $nh = (int) max(1, round($lh * $scale));

    $margin = 22;
    $padX = 14;
    $padY = 10;
    $bx = $w - $nw - $margin - $padX;
    $by = $h - $nh - $margin - $padY;
    $x1 = $bx - $padX;
    $y1 = $by - $padY;
    $x2 = $bx + $nw + $padX;
    $y2 = $by + $nh + $padY;

    imagealphablending($canvas, true);
    // Hafif yarı saydam beyaz plaka — her fotoğrafta logo okunur
    $plate = imagecolorallocatealpha($canvas, 255, 255, 255, 18);
    imagefilledrectangle($canvas, $x1, $y1, $x2, $y2, $plate);
    $edge = imagecolorallocatealpha($canvas, 255, 255, 255, 40);
    imagerectangle($canvas, $x1, $y1, $x2, $y2, $edge);

    $tmp = imagecreatetruecolor($nw, $nh);
    if ($tmp === false) {
        imagedestroy($logo);
        return;
    }
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);
    $clear = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
    imagefilledrectangle($tmp, 0, 0, $nw, $nh, $clear);
    imagealphablending($tmp, true);
    imagecopyresampled($tmp, $logo, 0, 0, 0, 0, $nw, $nh, $lw, $lh);
    imagecopy($canvas, $tmp, $bx, $by, 0, 0, $nw, $nh);

    imagedestroy($tmp);
    imagedestroy($logo);
}

function product_image_filesystem_path(array $product, int $index = 0): string
{
    $images = product_images($product);
    if (!$images || !isset($images[$index])) {
        return '';
    }
    $path = UPLOAD_PATH . '/' . ltrim($images[$index], '/');
    return is_file($path) ? $path : '';
}

function og_load_image(string $path): GdImage|false
{
    if ($path === '' || !is_file($path)) {
        return false;
    }
    $mime = '';
    if (class_exists('finfo')) {
        $mime = (string) (new finfo(FILEINFO_MIME_TYPE))->file($path);
    }
    return match ($mime) {
        'image/jpeg' => @imagecreatefromjpeg($path),
        'image/png' => @imagecreatefrompng($path),
        'image/webp' => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($path) : false,
        'image/gif' => @imagecreatefromgif($path),
        default => false,
    };
}

/**
 * 1200×630 paylaşım görseli.
 * Mod: product | product_logo | logo | custom (admin → Paylaşım Kartı).
 */
function product_og_card_build(array $product): string|false
{
    if (!function_exists('imagecreatetruecolor')) {
        return false;
    }

    $id = preg_replace('/[^a-zA-Z0-9_\-]/', '', (string) ($product['id'] ?? '')) ?? '';
    if ($id === '') {
        return false;
    }

    $dir = BASE_PATH . '/uploads/og';
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }

    $ver = substr(md5(product_og_cache_key($product)), 0, 8);
    $out = $dir . '/og_' . $id . '_' . $ver . '.jpg';
    if (is_file($out) && filesize($out) > 1000) {
        return $out;
    }

    foreach (glob($dir . '/og_' . $id . '_*.jpg') ?: [] as $old) {
        @unlink($old);
    }

    $w = OG_WIDTH;
    $h = OG_HEIGHT;
    $canvas = imagecreatetruecolor($w, $h);
    if ($canvas === false) {
        return false;
    }

    $mode = function_exists('og_share_image_mode') ? og_share_image_mode() : 'product_logo';
    if ($mode === 'custom' && function_exists('og_share_custom_image_path') && og_share_custom_image_path() === '') {
        $mode = 'product_logo';
    }

    if ($mode === 'logo') {
        og_fill_logo_canvas($canvas, $w, $h);
    } elseif ($mode === 'custom') {
        og_fill_cover_image($canvas, $w, $h, og_share_custom_image_path());
    } else {
        $bg = imagecolorallocate($canvas, 20, 20, 20);
        imagefilledrectangle($canvas, 0, 0, $w, $h, $bg);

        $srcPath = product_image_filesystem_path($product);
        $src = $srcPath !== '' ? og_load_image($srcPath) : false;

        if ($src !== false) {
            og_copy_cover($canvas, $src, $w, $h);
            imagedestroy($src);
        } else {
            $g1 = imagecolorallocate($canvas, 47, 107, 58);
            imagefilledrectangle($canvas, 0, 0, $w, $h, $g1);
        }

        if ($mode === 'product_logo') {
            og_overlay_site_logo($canvas, $w, $h);
        }
    }

    imagejpeg($canvas, $out, 92);
    imagedestroy($canvas);

    return is_file($out) ? $out : false;
}

/** Kaynak görseli 1200×630 cover olarak bas. */
function og_copy_cover(GdImage $canvas, GdImage $src, int $w, int $h): void
{
    $sw = imagesx($src);
    $sh = imagesy($src);
    if ($sw < 1 || $sh < 1) {
        return;
    }
    $scale = max($w / $sw, $h / $sh);
    $nw = (int) ceil($sw * $scale);
    $nh = (int) ceil($sh * $scale);
    $dx = (int) (($w - $nw) / 2);
    $dy = (int) (($h - $nh) / 2);
    imagecopyresampled($canvas, $src, $dx, $dy, 0, 0, $nw, $nh, $sw, $sh);
}

function og_fill_cover_image(GdImage $canvas, int $w, int $h, string $path): void
{
    $bg = imagecolorallocate($canvas, 20, 20, 20);
    imagefilledrectangle($canvas, 0, 0, $w, $h, $bg);
    $src = $path !== '' ? og_load_image($path) : false;
    if ($src === false) {
        $g1 = imagecolorallocate($canvas, 47, 107, 58);
        imagefilledrectangle($canvas, 0, 0, $w, $h, $g1);
        return;
    }
    og_copy_cover($canvas, $src, $w, $h);
    imagedestroy($src);
}

/** Sadece logo modu: marka zemin + ortalanmış logo. */
function og_fill_logo_canvas(GdImage $canvas, int $w, int $h): void
{
    $g1 = imagecolorallocate($canvas, 47, 107, 58);
    $g2 = imagecolorallocate($canvas, 36, 85, 45);
    imagefilledrectangle($canvas, 0, 0, $w, $h, $g1);
    imagefilledrectangle($canvas, 0, (int) ($h * 0.62), $w, $h, $g2);

    $logoPath = site_logo_filesystem_path();
    $logo = $logoPath !== '' ? og_load_image($logoPath) : false;
    if ($logo === false) {
        return;
    }

    $lw = imagesx($logo);
    $lh = imagesy($logo);
    if ($lw < 1 || $lh < 1) {
        imagedestroy($logo);
        return;
    }

    $maxW = (int) ($w * 0.42);
    $maxH = (int) ($h * 0.42);
    $scale = min($maxW / $lw, $maxH / $lh);
    $nw = (int) max(1, round($lw * $scale));
    $nh = (int) max(1, round($lh * $scale));
    $bx = (int) (($w - $nw) / 2);
    $by = (int) (($h - $nh) / 2);

    $pad = 28;
    imagealphablending($canvas, true);
    $plate = imagecolorallocatealpha($canvas, 255, 255, 255, 12);
    imagefilledrectangle($canvas, $bx - $pad, $by - $pad, $bx + $nw + $pad, $by + $nh + $pad, $plate);

    $tmp = imagecreatetruecolor($nw, $nh);
    if ($tmp === false) {
        imagedestroy($logo);
        return;
    }
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);
    $clear = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
    imagefilledrectangle($tmp, 0, 0, $nw, $nh, $clear);
    imagealphablending($tmp, true);
    imagecopyresampled($tmp, $logo, 0, 0, 0, 0, $nw, $nh, $lw, $lh);
    imagecopy($canvas, $tmp, $bx, $by, 0, 0, $nw, $nh);
    imagedestroy($tmp);
    imagedestroy($logo);
}

function og_font_path(bool $bold = false): string
{
    $candidates = $bold
        ? [
            'C:/Windows/Fonts/arialbd.ttf',
            'C:/Windows/Fonts/segoeuib.ttf',
            '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
            '/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf',
        ]
        : [
            'C:/Windows/Fonts/arial.ttf',
            'C:/Windows/Fonts/segoeui.ttf',
            '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
            '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf',
        ];
    foreach ($candidates as $f) {
        if (is_file($f)) {
            return $f;
        }
    }
    return '';
}

function og_fit_text(string $text, string $font, float $size, int $maxWidth): string
{
    if (!function_exists('imagettfbbox')) {
        return mb_substr($text, 0, 48);
    }
    $text = trim($text);
    $cut = false;
    while (mb_strlen($text) > 6) {
        $probe = $cut ? ($text . '…') : $text;
        $box = imagettfbbox($size, 0, $font, $probe);
        if ($box === false) {
            break;
        }
        $tw = abs($box[2] - $box[0]);
        if ($tw <= $maxWidth) {
            return $probe;
        }
        $text = mb_substr($text, 0, mb_strlen($text) - 1);
        $cut = true;
    }
    return $cut ? ($text . '…') : $text;
}

/** @return list<string> */
function og_wrap_text(string $text, string $font, float $size, int $maxWidth, int $maxLines = 2): array
{
    $text = trim($text);
    if ($text === '') {
        return [];
    }
    if (!function_exists('imagettfbbox')) {
        return [mb_substr($text, 0, 80)];
    }

    $words = preg_split('/\s+/u', $text) ?: [];
    $lines = [];
    $current = '';

    foreach ($words as $word) {
        $probe = $current === '' ? $word : ($current . ' ' . $word);
        $box = imagettfbbox($size, 0, $font, $probe);
        $tw = $box ? abs($box[2] - $box[0]) : 0;
        if ($tw <= $maxWidth) {
            $current = $probe;
            continue;
        }
        if ($current !== '') {
            $lines[] = $current;
            if (count($lines) >= $maxLines) {
                break;
            }
            $current = $word;
        } else {
            $lines[] = og_fit_text($word, $font, $size, $maxWidth);
            $current = '';
            if (count($lines) >= $maxLines) {
                break;
            }
        }
    }

    if ($current !== '' && count($lines) < $maxLines) {
        $lines[] = $current;
    } elseif ($current !== '' && $lines) {
        // Satır limiti doldu, son satıra … koy
        $last = (int) (count($lines) - 1);
        $lines[$last] = og_fit_text(rtrim($lines[$last], '…'), $font, $size, max(40, $maxWidth - 24));
        if (!str_ends_with($lines[$last], '…')) {
            $lines[$last] .= '…';
        }
    }

    $joined = implode(' ', $lines);
    if ($lines && mb_strlen($joined) < mb_strlen($text)) {
        $last = (int) (count($lines) - 1);
        if (!str_ends_with($lines[$last], '…')) {
            $lines[$last] = og_fit_text(rtrim($lines[$last], '…'), $font, $size, max(40, $maxWidth - 24));
            if (!str_ends_with($lines[$last], '…')) {
                $lines[$last] .= '…';
            }
        }
    }

    return $lines;
}

function og_latin(string $text): string
{
    $map = [
        'ş' => 's', 'Ş' => 'S', 'ı' => 'i', 'İ' => 'I', 'ğ' => 'g', 'Ğ' => 'G',
        'ü' => 'u', 'Ü' => 'U', 'ö' => 'o', 'Ö' => 'O', 'ç' => 'c', 'Ç' => 'C',
    ];
    return substr(strtr($text, $map), 0, 70);
}
