<?php

function sanitizeDynamicImageTitle($text) {
    $text = trim(strip_tags((string) $text));
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = str_replace(["\xe2\x86\x92", "\xc2\xab", "\xc2\xbb"], ['-', '-', '-'], $text);
    return mb_substr($text, 0, 100, 'UTF-8');
}

function buildDynamicImageUrl($base_url, $title, $mode = 'og') {
    $mode = ($mode === 'card') ? 'card' : 'og';
    $title = sanitizeDynamicImageTitle($title);
    if ($title === '') {
        $title = 'Kartvizit Market';
    }
    return rtrim($base_url, '/') . '/og-image.php?mode=' . $mode . '&title=' . rawurlencode($title);
}

function resolveOgImageUrl($base_url, $dynamic_content, $firma_adi, $slogan, $aktif_hizmet = null) {
    if ($dynamic_content && !empty($dynamic_content['h1'])) {
        return buildDynamicImageUrl($base_url, mb_substr($dynamic_content['h1'], 0, 80, 'UTF-8'), 'og');
    }
    if ($aktif_hizmet && !empty($aktif_hizmet['name'])) {
        return buildDynamicImageUrl($base_url, $aktif_hizmet['name'], 'og');
    }
    return buildDynamicImageUrl($base_url, $firma_adi . ' | ' . $slogan, 'og');
}

function resolveServiceCardImageUrl($base_url, $dynamic_content, $aktif_hizmet = null) {
    if ($dynamic_content && !empty($dynamic_content['h1'])) {
        return buildDynamicImageUrl($base_url, $dynamic_content['h1'], 'card');
    }
    if ($aktif_hizmet && !empty($aktif_hizmet['name'])) {
        return buildDynamicImageUrl($base_url, $aktif_hizmet['name'], 'card');
    }
    return buildDynamicImageUrl($base_url, 'Kartvizit Market', 'card');
}

function resolveHomeServiceCardImageUrl($base_url, $hizmet_name) {
    return buildDynamicImageUrl($base_url, $hizmet_name, 'card');
}

function sablonImageReady() {
    return file_exists(__DIR__ . '/images/sablon.png');
}
