<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

// Check admin authentication
if ((!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) &&
    (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true)) {
    // Allow test without auth
}

require_once 'db_config.php';

// $conn is already set by db_config.php
$db = $conn;

echo "<h1>SEO Manager - Debug Report</h1>";
echo "<hr>";

// 1. Check tables
echo "<h2>1. Database Tables</h2>";
$result = $db->query("SHOW TABLES");
$tables = [];
if ($result) {
    while ($row = $result->fetch_row()) {
        $tables[] = $row[0];
        echo "✓ " . $row[0] . "<br>";
    }
}
echo "<hr>";

// 2. Check products
echo "<h2>2. Products/Blogs Count</h2>";
if (in_array('products', $tables)) {
    $count = $db->query("SELECT COUNT(*) as cnt FROM products")->fetch_assoc()['cnt'];
    echo "✓ Products table: <strong>$count rows</strong><br>";
} else {
    echo "✗ Products table not found<br>";
}

if (in_array('blogs', $tables)) {
    $count = $db->query("SELECT COUNT(*) as cnt FROM blogs")->fetch_assoc()['cnt'];
    echo "✓ Blogs table: <strong>$count rows</strong><br>";
} else {
    echo "✗ Blogs table not found<br>";
}
echo "<hr>";

// 3. Check SEO metadata
echo "<h2>3. SEO Metadata</h2>";
if (in_array('seo_meta_tags', $tables)) {
    $count = $db->query("SELECT COUNT(*) as cnt FROM seo_meta_tags")->fetch_assoc()['cnt'];
    echo "✓ SEO Meta Tags: <strong>$count rows</strong><br>";
    
    // Sample data
    $result = $db->query("SELECT page_type, page_id, title FROM seo_meta_tags LIMIT 5");
    if ($result && $result->num_rows > 0) {
        echo "<div style='margin-left: 20px; margin-top: 10px;'>";
        echo "<strong>Sample SEO Data:</strong><br>";
        while ($row = $result->fetch_assoc()) {
            echo "• {$row['page_type']} #{$row['page_id']}: {$row['title']}<br>";
        }
        echo "</div>";
    }
} else {
    echo "✗ SEO Meta Tags table not found<br>";
}
echo "<hr>";

// 4. Test AJAX endpoint
echo "<h2>4. Test AJAX Load Products</h2>";
if (isset($_GET['test_ajax'])) {
    $_POST['action'] = 'load_products';
    
    // Simulate AJAX call
    if (in_array('blogs', $tables)) {
        $query = "SELECT id, title, description FROM blogs ORDER BY id DESC LIMIT 100";
        $result = $db->query($query);
        
        $products = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $seo_query = "SELECT * FROM seo_meta_tags WHERE page_type='product' AND page_id=" . intval($row['id']);
                $seo_result = $db->query($seo_query);
                $seo_data = $seo_result ? $seo_result->fetch_assoc() : null;
                
                $products[] = [
                    'id' => $row['id'],
                    'title' => $row['title'],
                    'seo_score' => $seo_data ? 75 : 0,
                    'seo_title' => $seo_data['title'] ?? 'Not set'
                ];
            }
        }
        
        echo "<pre>";
        echo json_encode(['success' => true, 'products' => $products, 'count' => count($products)], JSON_PRETTY_PRINT);
        echo "</pre>";
    }
} else {
    echo "<a href='?test_ajax=1' style='padding: 10px 20px; background: #d16baf; color: white; text-decoration: none; border-radius: 4px;'>Test Load Products AJAX</a>";
}
echo "<hr>";

// 5. Sample blogs
echo "<h2>5. Sample Blogs Data</h2>";
if (in_array('blogs', $tables)) {
    $result = $db->query("SELECT id, title FROM blogs LIMIT 10");
    if ($result && $result->num_rows > 0) {
        echo "<ul>";
        while ($row = $result->fetch_assoc()) {
            echo "<li>ID {$row['id']}: {$row['title']}</li>";
        }
        echo "</ul>";
    }
}
echo "<hr>";

// 6. PHP Logs
echo "<h2>6. Check PHP Error Log</h2>";
$log_file = 'C:\\xampp\\apache\\logs\\error.log';
if (file_exists($log_file)) {
    $lines = file_tail($log_file, 20);
    echo "<pre style='background: #f5f5f5; padding: 10px; max-height: 300px; overflow-y: auto;'>";
    foreach ($lines as $line) {
        echo htmlspecialchars($line);
    }
    echo "</pre>";
} else {
    echo "Log file not found";
}
echo "<hr>";

// Function to get last N lines of a file
function file_tail($file, $lines = 20) {
    if (!file_exists($file)) return [];
    $handle = fopen($file, 'r');
    $file_size = filesize($file);
    $buffer_size = 8192;
    $lines_found = 0;
    $pos = $file_size;
    $data = '';
    
    while ($pos > 0 && $lines_found < $lines) {
        $pos = max($pos - $buffer_size, 0);
        fseek($handle, $pos);
        $chunk = fread($handle, $file_size - $pos);
        $data = $chunk . $data;
        $lines_found = substr_count($data, "\n");
    }
    
    fclose($handle);
    
    $lines_arr = explode("\n", trim($data));
    return array_slice($lines_arr, -$lines);
}

$db->close();
?>
