<?php
/**
 * IndexNow submission script for vivapy.com
 * Run: php indexnow-submit.php
 * Cron example: every 6 hours
 */

define('INDEXNOW_ENDPOINT', 'https://api.indexnow.org/indexnow');
define('KEY', 'vivapy-7k3x2m9p4r8q5w8');
define('HOST', 'vivapy.com');
define('KEY_LOCATION', 'https://vivapy.com/' . KEY . '.txt');

$sitemap = __DIR__ . '/sitemap.xml';

if (!file_exists($sitemap)) {
    fwrite(STDERR, "Sitemap not found: $sitemap\n");
    exit(1);
}

$xml = simplexml_load_file($sitemap);
if ($xml === false) {
    fwrite(STDERR, "Failed to parse sitemap\n");
    exit(1);
}

$urls = [];
foreach ($xml->url as $entry) {
    $loc = (string) $entry->loc;
    if ($loc) {
        $urls[] = $loc;
    }
}

if (empty($urls)) {
    fwrite(STDERR, "No URLs found in sitemap\n");
    exit(1);
}

$payload = [
    'host' => HOST,
    'key' => KEY,
    'keyLocation' => KEY_LOCATION,
    'urlList' => $urls,
];

$ch = curl_init(INDEXNOW_ENDPOINT);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_FOLLOWLOCATION => true,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    fwrite(STDERR, "cURL error: $error\n");
    exit(1);
}

echo "IndexNow submission for " . HOST . ":\n";
echo "  HTTP status: $httpCode\n";
echo "  URLs submitted: " . count($urls) . "\n";
echo "  Response: " . ($response ?: '(empty)') . "\n";

if ($httpCode >= 200 && $httpCode < 300) {
    echo "  Status: OK\n";
    exit(0);
} else {
    echo "  Status: FAILED\n";
    exit(1);
}
