<?php
header('Content-Type: text/html; charset=utf-8');
$path="../../../";
include("cevir.php");
$path2="config/"; include("".$path."config/map.php");
include("fonksiyon".$ver.".php");

echo '<script src="//code.jquery.com/jquery-latest.js" type="text/javascript"></script>';

// ---------- AYARLAR ---------- //
$keywords = explode("+",tanim("tags","n1",0));
$multilocation = "false";
if (!empty(explode("+", tanim("tags", "n2", 0)))){$multilocation = "true";}

// Lokasyon Promptu
$locationInstruction = "";
if ($multilocation === "true") {
    $locationInstruction = " Yazı içerisinde {city} şehrine yerel bir atıfta bulunarak, hizmetin {city} bölgesinde de verildiğini doğal bir dille hissettir. Sadece {city} kelimesini geçir, süslü ifadelerden kaçın.";
}

$apiKey = tanim("openai","n1",0); 
$pexelsApiKey = "HKnBYC6ckwO0SYifayYWkBEUowRSWIIBIPETYUBLju0QwBFvbmnaHK0F";
$apl = isset($_GET["apl"]) && !empty($_GET["apl"]) ? $_GET["apl"] : "tr";

// ---------- API İSTEK FONKSİYONU (Sadece Makale İçin Kullanılacak) ---------- //
function fetchFromAPI($systemMsg, $userMsg, $apiUrl, $apiKey) {
    $data = [
        "model" => "gpt-4o-mini",
        "messages" => [
            ["role" => "system", "content" => $systemMsg],
            ["role" => "user", "content" => $userMsg]
        ],
        "max_tokens" => 2000,
        "temperature" => 0.7,
    ];

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer " . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    if (curl_errno($ch)) { return ""; } 
    curl_close($ch);
    
    $responseData = json_decode($response, true);
    $content = $responseData['choices'][0]['message']['content'] ?? '';
    $content = str_replace(['```html', '```', '"', "'", '.'], '', $content);
    return trim($content);
}

// ---------- İÇERİK ÜRETİMİ ---------- //
function generateBlogContent($apiKey, $keyword, $languageOption = 'tr') {
    global $firma, $fdesc, $locationInstruction;
    $apiUrl = "https://api.openai.com/v1/chat/completions";
    
    // (Promptlar kısaltıldı, yer kaplamaması için)
    $systemPrompt = "Sen SEO uzmanı profesyonel bir yazarsın. Saf HTML kodu ver.";
    $titlePromptTr = "Konu: '$keyword'. Firma: '$firma'. GÖREV: 60-70 karakteri geçmeyen blog başlığı yaz. Tırnak yok.";
    $descPromptTr = "Konu: '$keyword'. GÖREV: 160 karakteri geçmeyen meta description yaz.";
    $contentPromptTr = "Konu: '$keyword'. Firma: '$firma'. GÖREV: HTML formatında detaylı blog yazısı yaz.";

    $titlePromptEn = "Topic: '$keyword'. TASK: Write a catchy title under 70 chars.";
    $descPromptEn = "Topic: '$keyword'. TASK: Write a meta description under 160 chars.";
    $contentPromptEn = "Topic: '$keyword'. TASK: Write a blog post in HTML.";

    $result = [];
    if ($languageOption === 'tr' || $languageOption === 'both') {
        $result['turkish'] = [
            "title" => fetchFromAPI("Başlık uzmanısın.", $titlePromptTr, $apiUrl, $apiKey),
            "description" => fetchFromAPI("SEO uzmanısın.", $descPromptTr, $apiUrl, $apiKey),
            "content" => fetchFromAPI($systemPrompt, $contentPromptTr, $apiUrl, $apiKey),
        ];
    }
    if ($languageOption === 'en' || $languageOption === 'both') {
        $result['english'] = [
            "title" => fetchFromAPI("Headline expert.", $titlePromptEn, $apiUrl, $apiKey),
            "description" => fetchFromAPI("SEO expert.", $descPromptEn, $apiUrl, $apiKey),
            "content" => fetchFromAPI($systemPrompt, $contentPromptEn, $apiUrl, $apiKey),
        ];
    }
    return $result;
}

// ---------- API KULLANMAYAN GÖRSEL FONKSİYONU ---------- //
function searchImageOnPexels($keyword, $pexelsApiKey) {
    // 1. ADIM: Türkçe kelimeyi doğrudan dene (Bedava)
    $foundUrl = runPexelsCurl($keyword, $pexelsApiKey);
    if ($foundUrl) return $foundUrl;

    // 2. ADIM: Bulamazsa genel 'business' kategorisinden getir (Bedava)
    $foundUrl = runPexelsCurl("business", $pexelsApiKey);
    if ($foundUrl) return $foundUrl;

    // 3. ADIM: Yine bulamazsa 'office' kategorisinden getir (Bedava)
    $foundUrl = runPexelsCurl("office", $pexelsApiKey);
    if ($foundUrl) return $foundUrl;

    // 4. ADIM: Hiçbiri olmazsa 'technology' (Bedava)
    $foundUrl = runPexelsCurl("technology", $pexelsApiKey);
    return $foundUrl; 
}

// Pexels İstek Yardımcısı
function runPexelsCurl($query, $apiKey) {
    // Locale parametresi eklendi, Türkçe sonuç ihtimalini artırır
    $url = "https://api.pexels.com/v1/search?query=" . urlencode($query) . "&orientation=landscape&per_page=1&locale=tr-TR";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $apiKey));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $result = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    
    if ($err) return null;
    
    $data = json_decode($result, true);
    if (isset($data['photos']) && count($data['photos']) > 0) {
        return $data['photos'][0]['src']['large2x'];
    }
    return null;
}

// ---------- ANA AKIŞ ---------- //
$selectedKeyword = $keywords[array_rand($keywords)];
if($_POST["tag"]<>""){$selectedKeyword=$_POST["tag"];}

$blogData = generateBlogContent($apiKey, $selectedKeyword, $apl);

if($ver=="7" && !$conn->ping()){$conn->close();$conn=mysqli_connect($V3Server,$V3User,$V3Pass,$V3Db);mysqli_set_charset($conn,'utf8');}

if($_GET["id"]==""){
    $insertedId = null;
    // Türkçe Kayıt
    if($_GET["apl"]=="" or $_GET["apl"]=="tr" or $_GET["apl"]=="both"){
        $titleTr = str_replace(['"', "'"], '', $blogData['turkish']['title']);
        $contentTr = $blogData['turkish']['content']; 
        $descTr = $blogData['turkish']['description'];
        $Rs = $conn->query("insert into lang1 (ne,t1,n1,n2,s2,s13,ts1) values ('haber', '".addslashes(stripslashes($titleTr))."', '".addslashes(stripslashes($contentTr))."', '".addslashes(stripslashes($descTr))."', '".$_GET["catID"]."', '1', now())");
        if ($Rs) { $insertedId = $conn->insert_id; }
    }
    // İngilizce Kayıt
    if($_GET["apl"]=="en" or $_GET["apl"]=="both"){
        $titleEn = str_replace(['"', "'"], '', $blogData['english']['title']);
        $contentEn = $blogData['english']['content'];
        $descEn = $blogData['english']['description'];
        $Rs = $conn->query("insert into lang2 (id,ne,t1,n1,n2,s2,s13,ts1) values ('".$id."','haber', '".addslashes(stripslashes($titleEn))."', '".addslashes(stripslashes($contentEn))."', '".addslashes(stripslashes($descEn))."', '".$_GET["catID"]."', '1', now())");
        if ($Rs) { $insertedId = $conn->insert_id; }
    }

    if ($insertedId !== null) {
        $file = findDirectoryPath("deppo").'/seo_monitor.json';
        $domain = $_SERVER['HTTP_HOST'];
        $data = file_exists($file) ? json_decode(file_get_contents($file), true) : [];
        $newEntry = ['Id' => $insertedId, 'title' => addslashes(stripslashes($titleTr)), 'description' => addslashes(stripslashes($descTr)), 'domain' => $domain, 'date' => date('Y-m-d H:i:s'), 'time' => time()];
        array_unshift($data, $newEntry);
        if (count($data) > 3) { array_pop($data); }
        file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        
        if($_GET["img"]=="" or $_GET["img"]=="true"){
            echo "<script>jQuery(document).ready(function(){location.href='".$weburl."/deppo/tools/script/autopilot.php?id=".$insertedId."&key=".base64_encode($selectedKeyword)."';});</script>";
        }
    }

} else {
    // ---------- RESİM İŞLEME BÖLÜMÜ (OPENAI KULLANILMIYOR) ---------- //
    
    // 1. Temizle
    $rawInput = base64_decode($_GET["key"]);
    if (strpos($rawInput, ',') !== false) {
        $parts = explode(',', $rawInput);
        $primaryKeyword = trim($parts[0]);
    } else {
        $primaryKeyword = $rawInput;
    }
    
    // 2. Doğrudan Pexels'e Sor (Çeviri yok)
    // Eğer Türkçe bulamazsa, otomatik olarak 'business' veya 'office' getirecek.
    $blogImage = searchImageOnPexels($primaryKeyword, $pexelsApiKey);
    
    if ($blogImage) {
        $imageString = file_get_contents($blogImage);
        $url_parts = parse_url($blogImage);
        $path_info = pathinfo($url_parts['path']);
        $uzanti = isset($path_info['extension']) ? $path_info['extension'] : 'jpg';
        
        $cleanKeyword = str_replace("...","",kisalt($primaryKeyword,2));
        
        $save = file_put_contents("../../image/".date('dmYHis')."_".cevir($cleanKeyword).".".$uzanti."", $imageString);
        $save = file_put_contents("../../image/k_".date('dmYHis')."_".cevir($cleanKeyword).".".$uzanti."", $imageString);
        
        $rsi = $conn->query("insert into medya(ne,t3,t1,s1,s2,s3) values ('resim', 'haber', '".date('dmYHis')."_".cevir($cleanKeyword).".".$uzanti."', '".$_GET["id"]."', '1', '0')");
        
        echo "<div style='background:#eef; padding:10px; border:1px solid #ccf;'>";
        echo "Aranan Kelime: $primaryKeyword (ChatGPT Kullanılmadı) <br> Sonuç: Görsel Eklendi.";
        echo "</div>";
        echo "<img src='".$blogImage."' style='max-width:100%;'>";
    } else {
        echo "Hiçbir görsel (yedekler dahil) bulunamadı.";
    }
}
?>