<?php
// Suppress deprecation warnings from third-party libraries BEFORE any includes
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
ini_set('display_errors', 1);

session_start();

require '../../config.php';
require '../admin_config.php';
require '../functions.php';
require '../views/header.view.php';

if (isset($_SESSION['user_email'])){

$connect = connect($database);
if(!$connect){
    header('Location: ./error.php');
}

$check_access = check_access($connect);

if ($check_access['user_role'] == 1){
    
    // Load API configuration
    $apiConfigFile = '../../seo_api_config.json';
    $apiConfig = [];
    if (file_exists($apiConfigFile)) {
        $apiConfig = json_decode(file_get_contents($apiConfigFile), true);
    }
    
    // Handle API configuration save
    if (isset($_POST['action']) && $_POST['action'] == 'save_api_config') {
        $apiConfig = [
            'google_service_account' => $_POST['google_service_account'] ?? '',
            'bing_api_key' => $_POST['bing_api_key'] ?? ''
        ];
        
        if (file_put_contents($apiConfigFile, json_encode($apiConfig, JSON_PRETTY_PRINT))) {
            $success = "API configuration saved successfully!";
        } else {
            $error = "Failed to save API configuration.";
        }
    }
    
    // Handle sitemap generation
    if (isset($_POST['action']) && $_POST['action'] == 'generate_sitemap') {
        try {
            // Generate sitemap
            $sitemapUrl = SITE_URL . '/sitemap_auto.php';
            $sitemapContent = @file_get_contents($sitemapUrl);
            
            if ($sitemapContent) {
                file_put_contents('../../sitemap.xml', $sitemapContent);
                $success = "Sitemap generated successfully!";
            } else {
                $error = "Failed to generate sitemap.";
            }
        } catch (Exception $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
    
    // Handle sitemap submission to search engines
    if (isset($_POST['action']) && $_POST['action'] == 'submit_sitemap') {
        $submitted = [];
        
        $sitemapUrl = urlencode(SITE_URL . '/sitemap.xml');
        
        // Google
        $googleUrl = "https://www.google.com/ping?sitemap=" . $sitemapUrl;
        @file_get_contents($googleUrl);
        $submitted[] = "Google";
        
        // Bing
        $bingUrl = "https://www.bing.com/ping?sitemap=" . $sitemapUrl;
        @file_get_contents($bingUrl);
        $submitted[] = "Bing";
        
        $success = "Sitemap submitted to: " . implode(', ', $submitted);
    }
    
    // Handle robots.txt update
    if (isset($_POST['action']) && $_POST['action'] == 'update_robots') {
        $robotsContent = $_POST['robots_content'];
        
        if (file_put_contents('../../robots.txt', $robotsContent)) {
            $success = "robots.txt updated successfully!";
        } else {
            $error = "Failed to update robots.txt";
        }
    }
    
    // Get current robots.txt content
    $robotsContent = file_exists('../../robots.txt') ? file_get_contents('../../robots.txt') : '';
    
    // Get sitemap stats
    $sitemapExists = file_exists('../../sitemap.xml');
    $sitemapSize = $sitemapExists ? filesize('../../sitemap.xml') : 0;
    $sitemapDate = $sitemapExists ? date('Y-m-d H:i:s', filemtime('../../sitemap.xml')) : 'Never';
    
    // Count URLs with error handling
    try {
        $totalPages = $connect->query("SELECT COUNT(*) FROM pages WHERE page_status = 1")->fetchColumn();
    } catch (Exception $e) {
        $totalPages = 0;
    }
    
    try {
        $totalPosts = $connect->query("SELECT COUNT(*) FROM blog_posts WHERE post_status = 'published'")->fetchColumn();
    } catch (Exception $e) {
        $totalPosts = 0;
    }
    
    try {
        $totalStores = $connect->query("SELECT COUNT(*) FROM stores WHERE store_status = 1")->fetchColumn();
    } catch (Exception $e) {
        $totalStores = 0;
    }
    
    try {
        $totalCategories = $connect->query("SELECT COUNT(*) FROM categories WHERE category_status = 1")->fetchColumn();
    } catch (Exception $e) {
        $totalCategories = 0;
    }
    
    try {
        $totalCoupons = $connect->query("SELECT COUNT(*) FROM coupons WHERE coupon_status = 1")->fetchColumn();
    } catch (Exception $e) {
        $totalCoupons = 0;
    }
    
    $totalUrls = $totalPages + $totalPosts + $totalStores + $totalCategories + $totalCoupons + 10;
    
    require '../views/seo_tools_enhanced.view.php';
	
}else{
	header('Location:'.SITE_URL);
}

require '../views/footer.view.php';

}else{
	header('Location: ./login.php');	
}

?>
