<?php
/**
 * API - Sitemap Generator
 */

header('Content-Type: application/json');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

$action = $_GET['action'] ?? '';

// Generate Sitemap (can be called by cron)
if ($action === 'generate') {
    // Optional: Check for secret key for cron access
    $secret = $_GET['secret'] ?? '';
    $isAdmin = auth()->isAdminLoggedIn();
    
    if (!$isAdmin && $secret !== 'your-cron-secret-key') {
        // Allow public access for now
    }
    
    $baseUrl = rtrim(SITE_URL, '/');
    
    // Get pages from database
    $pages = dbFetchAll("SELECT * FROM seo_pages WHERE status = 'active'");
    
    // Start XML
    $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    
    // Homepage
    $xml .= "  <url>\n";
    $xml .= "    <loc>{$baseUrl}/</loc>\n";
    $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    $xml .= "    <changefreq>daily</changefreq>\n";
    $xml .= "    <priority>1.0</priority>\n";
    $xml .= "  </url>\n";
    
    // Database pages
    foreach ($pages as $page) {
        $url = $baseUrl . '/' . ltrim($page['page_url'], '/');
        $lastmod = date('Y-m-d', strtotime($page['updated_at']));
        
        $xml .= "  <url>\n";
        $xml .= "    <loc>{$url}</loc>\n";
        $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
        $xml .= "    <changefreq>weekly</changefreq>\n";
        $xml .= "    <priority>0.8</priority>\n";
        $xml .= "  </url>\n";
    }
    
    // Static pages
    $staticPages = [
        ['url' => 'user/login.php', 'priority' => 0.7, 'freq' => 'monthly'],
        ['url' => 'user/register.php', 'priority' => 0.8, 'freq' => 'monthly'],
        ['url' => 'user/trade.php', 'priority' => 0.9, 'freq' => 'weekly'],
        ['url' => 'user/dashboard.php', 'priority' => 0.6, 'freq' => 'weekly'],
        ['url' => 'user/deposit.php', 'priority' => 0.7, 'freq' => 'weekly'],
        ['url' => 'user/withdraw.php', 'priority' => 0.6, 'freq' => 'weekly'],
    ];
    
    foreach ($staticPages as $sp) {
        $xml .= "  <url>\n";
        $xml .= "    <loc>{$baseUrl}/{$sp['url']}</loc>\n";
        $xml .= "    <changefreq>{$sp['freq']}</changefreq>\n";
        $xml .= "    <priority>{$sp['priority']}</priority>\n";
        $xml .= "  </url>\n";
    }
    
    $xml .= '</urlset>';
    
    // Save to file
    $filepath = ROOT_PATH . '/sitemap.xml';
    $result = file_put_contents($filepath, $xml);
    
    if ($result !== false) {
        jsonSuccess('Sitemap generated', [
            'path' => $filepath,
            'url' => $baseUrl . '/sitemap.xml',
            'pages' => count($pages) + count($staticPages) + 1,
            'size' => strlen($xml)
        ]);
    } else {
        jsonError('Failed to write sitemap file');
    }
}

// View Sitemap
if ($action === 'view') {
    $filepath = ROOT_PATH . '/sitemap.xml';
    
    if (file_exists($filepath)) {
        header('Content-Type: application/xml');
        readfile($filepath);
        exit;
    }
    
    jsonError('Sitemap not found');
}

// Ping Search Engines
if ($action === 'ping') {
    if (!auth()->isAdminLoggedIn()) {
        jsonError('Unauthorized', 401);
    }
    
    $sitemapUrl = urlencode(SITE_URL . '/sitemap.xml');
    $results = [];
    
    // Ping Google
    $googleUrl = "https://www.google.com/ping?sitemap={$sitemapUrl}";
    $ch = curl_init($googleUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $results['google'] = ['status' => $httpCode == 200 ? 'success' : 'failed', 'code' => $httpCode];
    
    // Ping Bing
    $bingUrl = "https://www.bing.com/ping?sitemap={$sitemapUrl}";
    $ch = curl_init($bingUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $results['bing'] = ['status' => $httpCode == 200 ? 'success' : 'failed', 'code' => $httpCode];
    
    jsonSuccess('Search engines pinged', ['results' => $results]);
}

jsonError('Invalid action');
