<?php

header("Content-Type: image/gif");

echo base64_decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"); // Returns a 1x1 transparent pixel



// 1. ENVIRONMENT SETUP

ini_set('display_errors', 1); 

error_reporting(E_ALL);

ignore_user_abort(true); 

set_time_limit(60);   



$apiKey = 'AIzaSyALx9xFHFBx62gA97uqoSeifktNcQQyO30'; 

$dataFile = 'data.json'; 

$statusFile = 'generator_status.json';

$sitemapFile = 'sitemap.xml';

$baseUrl = "https://tenmilliontrends.com/";

$modelId = ""; 



// 📁 TARGET DIRECTORY CONFIGURATION

$blogFolder = 'blog/'; 

if (!file_exists($blogFolder)) {

    mkdir($blogFolder, 0755, true); // Create the folder if it doesn't exist

}



// Exit if data doesn't exist

if (!file_exists($dataFile)) {

    die("Error: data.json not found in " . getcwd());

}



// 2. LOAD DATA & STATUS

$data = json_decode(file_get_contents($dataFile), true);

$topics = array_keys($data);

$actions = ["Ideas", "Summary", "SEO", "Growth", "Money", "Social", "Health", "Truth", "History", "Research"];

$status = file_exists($statusFile) ? json_decode(file_get_contents($statusFile), true) : ['last_run' => 0];

$currentTime = time();



// 3. GENERATION LOGIC (Runs every 105 seconds)

if ($currentTime - $status['last_run'] >= 105) {

   

    $topic = $topics[array_rand($topics)];

    $action = $actions[array_rand($actions)];

    

    $affiliateLinks = [


    ];



    $affiliateContext = "Include 2-3 of these specific affiliate links naturally:\n";

    foreach ($affiliateLinks as $item) {

        $affiliateContext .= "- " . $item['title'] . ": " . $item['link'] . " (" . $item['desc'] . ")\n";

    }



    $prompt = "Write a high-quality blog post about '$topic' ($action). 

               - DO NOT include <html>, <head>, or <body> tags.

               - Start directly with <h2> or <h3> headings.

               - Use <p>, <ul>, and <li> for the content.

               - Include 3-5 links to: {$baseUrl}?q=" . urlencode($topic) . " using natural anchor text.

               - AFFILIATE REQUIREMENTS: $affiliateContext";



    $articleHtml = callGemini($modelId, $apiKey, $prompt);



    if ($articleHtml) {

        // Clean formatting

        $articleHtml = preg_replace('/^```html|```$/m', '', $articleHtml);

        $safeName = strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $topic . '-' . $action));

        

        // Prepended the blog directory path here

        $fileName = $safeName . ".php";

        $targetFilePath = $blogFolder . $fileName; 



        // Image Handling

        $pixabayKey = '7771164-b7580672d32baea7e7944f3a5';

        $imageUrl = getPixabayImage($pixabayKey, $topic);

        $imageHtml = $imageUrl ? "<figure class='featured-image'><img src='{$imageUrl}' alt='" . htmlspecialchars($topic) . "' style='width:100%; height:auto; border-radius:8px;'></figure>" : "";

        

        $articleHtml = $imageHtml . $articleHtml;



        // Construct full file content with internal styles

        $fullHtml = "<?php

\$ip = \$_SERVER['REMOTE_ADDR'];

\$logData = ['ts' => gmdate('c'), 'event' => 'ssr_pageview', 'ip' => \$ip, 'page' => \$_SERVER['REQUEST_URI']];

file_put_contents(dirname(__DIR__) . '/data/views.jsonl', json_encode(\$logData) . \"\\n\", FILE_APPEND | LOCK_EX);

?>

<!DOCTYPE html>

<html lang='en'>

<head>

<!-- Google tag (gtag.js) -->

<script async src='https://www.googletagmanager.com/gtag/js?id=G-L8P9KKJKH2'></script>

<script>

  window.dataLayer = window.dataLayer || [];

  function gtag(){dataLayer.push(arguments);}

  gtag('js', new Date());

  gtag('config', 'G-L8P9KKJKH2');

</script>



<meta name='robots' content='index, follow'>



    <meta charset='UTF-8'>

    <meta name='viewport' content='width=device-width, initial-scale=1.0'>

    <title>$topic $action | Ten Million Trends</title>

    <style>

        body { background-color: #0f0f0f; margin: 0; padding: 20px; font-family: 'Segoe UI', Roboto, sans-serif; }

        #gemini-content { max-width: 800px; margin: 40px auto; background: linear-gradient(145deg, #1e1e1e 0%, #121212 100%); padding: 40px; border: 2px solid rgba(255, 255, 255, 0.8); border-radius: 20px; box-shadow: 0 20px 50px rgba(0,0,0,0.7); color: #dcdcdc; line-height: 1.8; }

        .featured-image img { border: 2px solid #ffffff; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 10px 20px rgba(0,0,0,0.4); }

        #gemini-content h2, #gemini-content h3 { color: #ffffff; margin-top: 1.6em; border-left: 4px solid #ffffff; padding-left: 15px; }

        #gemini-content a { color: #00aaff; text-decoration: none; font-weight: bold; }

        #gemini-content a:hover { text-decoration: underline; }

    </style>

</head>

<body id='tmt-engine-root'>

    <div id='app-container'> 

        <main id='main-content'>

            <article id='gemini-content'>$articleHtml</article>

        </main>

    </div>

</body>

</html>";



        // Save file into folder and pass the corrected folder path to sitemap

        if (file_put_contents($targetFilePath, $fullHtml)) {

            updateSitemap($blogFolder . $fileName, $baseUrl, $sitemapFile);

            $status['last_run'] = $currentTime;

            $status['last_file'] = $targetFilePath;

            file_put_contents($statusFile, json_encode($status));

            echo "Successfully generated: $targetFilePath";

        }

    }

} else {

    echo "Wait " . (105 - ($currentTime - $status['last_run'])) . " more seconds.";

}



// Helper Functions

function updateSitemap($newFile, $baseUrl, $sitemapFile) {

    $url = $baseUrl . $newFile;

    $date = date('Y-m-d');

    if (!file_exists($sitemapFile)) {

        file_put_contents($sitemapFile, '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');

    }

    $dom = new DOMDocument('1.0', 'UTF-8');

    $dom->formatOutput = true;

    if (!@$dom->load($sitemapFile)) return;

    $xpath = new DOMXPath($dom);

    $xpath->registerNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9');

    if ($xpath->query("//s:loc[text()='$url']")->length > 0) return;

    $urlset = $dom->documentElement;

    $urlNode = $dom->createElement('url');

    $urlNode->appendChild($dom->createElement('loc', htmlspecialchars($url)));

    $urlNode->appendChild($dom->createElement('lastmod', $date));

    $urlset->appendChild($urlNode);

    $dom->save($sitemapFile);

}



function callGemini($model, $key, $prompt) {

    $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$key}";

    $payload = ["contents" => [["parts" => [["text" => $prompt]]]]];

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);

    $result = json_decode($response, true);

    return $result['candidates'][0]['content']['parts'][0]['text'] ?? null;

}



function getPixabayImage($apiKey, $query) {

    $query = urlencode(implode(' ', array_slice(explode(' ', $query), 0, 3)));

    $url = "https://pixabay.com/api/?key={$apiKey}&q={$query}&image_type=photo&per_page=3";

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);

    $result = json_decode($response, true);

    return $result['hits'][0]['webformatURL'] ?? null;

}

?>