<?php
/**
 * Admin SEO Manager - Main Interface
 * Comprehensive SEO management for admin users only
 */

// Start output buffering to catch any stray output from includes
ob_start();

session_start();

// Use centralized database configuration
require_once __DIR__ . '/db_config.php';

// Check for AJAX requests FIRST, before including anything
$is_ajax_request = ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']));

// Include dependencies early for AJAX requests
@require_once 'db_config.php';
@require_once 'seo_plugin.php';
@require_once 'seo_readability.php';
@require_once 'seo_keywords.php';
@require_once 'seo_schema.php';
@require_once 'seo_analytics.php';
@require_once 'seo_site_auditor.php';
@require_once 'seo_db_schema.php';
@require_once 'seo_helper_advanced.php';
@require_once 'classes/YoastSEOAnalyzer.php';

// Clean the output buffer (discard any accidental output from includes)
ob_end_clean();

// Initialize Database Connection using centralized config
$db = $conn;

// Check connection
if ($db->connect_error) {
    if ($is_ajax_request) {
        header('Content-Type: application/json');
        die(json_encode(['success' => false, 'message' => 'Database connection failed: ' . $db->connect_error]));
    }
    die("Connection failed: " . $db->connect_error);
}

// Handle AJAX requests BEFORE further initialization
if ($is_ajax_request) {
    try {
        // For AJAX requests, we'll initialize classes on demand
        handle_ajax_request($_POST);
    } catch (Exception $e) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
        exit;
    }
}

// Create SEO tables if they don't exist
ensure_seo_tables_exist($db);

// Initialize SEO classes
$seo_plugin = new SEOPlugin($db_config);
$analytics = new SEOAnalytics($db);

// Check admin authentication (support both session variable names for compatibility)
if ((!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) &&
    (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true)) {
    header('Location: admin_login.php');
    exit;
}

// Get current action
$action = $_GET['action'] ?? 'dashboard';
$page_type = $_GET['page_type'] ?? '';
$page_id = $_GET['page_id'] ?? '';

function handle_ajax_request($data) {
    global $seo_plugin, $analytics, $db_config, $db;
    
    header('Content-Type: application/json');
    
    // Initialize SEO classes if not already done (for early AJAX requests)
    if (!isset($GLOBALS['seo_plugin']) || $GLOBALS['seo_plugin'] === null) {
        // Ensure tables exist first
        ensure_seo_tables_exist($db);
        $GLOBALS['seo_plugin'] = new SEOPlugin($db_config);
    }
    
    if (!isset($GLOBALS['analytics']) || $GLOBALS['analytics'] === null) {
        $GLOBALS['analytics'] = new SEOAnalytics($db);
    }
    
    $seo_plugin = $GLOBALS['seo_plugin'];
    $analytics = $GLOBALS['analytics'];
    
    switch ($data['action']) {
        case 'save_seo':
            save_seo_data($data);
            break;
        case 'analyze_readability':
            analyze_readability($data);
            break;
        case 'analyze_keywords':
            analyze_keywords($data);
            break;
        case 'get_analytics':
            get_analytics_data($data);
            break;
        case 'generate_schema':
            generate_schema_ajax($data);
            break;
        case 'audit_page':
            audit_page_handler($data);
            break;
        case 'analyze_content':
            analyze_content_handler($data);
            break;
        case 'load_products':
            load_products_ajax($data);
            break;
        case 'load_blogs':
            load_blogs_ajax($data);
            break;
        case 'load_categories':
            load_categories_ajax($data);
            break;
        case 'save_product_seo':
            save_product_seo($data);
            break;
        case 'save_blog_seo':
            save_blog_seo($data);
            break;
        case 'analyze_yoast_seo':
            analyze_yoast_seo($data);
            break;
        case 'suggest_internal_links':
            suggest_internal_links($data);
            break;
        case 'bulk_apply_seo':
            bulk_apply_seo($data);
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit;
}

function save_seo_data($data) {
    global $seo_plugin;
    
    try {
        $result = $seo_plugin->saveSEOData(
            $data['page_type'] ?? '',
            $data['page_id'] ?? 0,
            $data
        );
        
        echo json_encode([
            'success' => $result,
            'message' => $result ? 'SEO data saved successfully' : 'Error saving SEO data'
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function analyze_readability($data) {
    try {
        $content = $data['content'] ?? '';
        
        if (empty($content)) {
            echo json_encode(['success' => false, 'message' => 'No content provided']);
            return;
        }
        
        $analysis = ReadabilityAnalyzer::analyze($content);
        
        echo json_encode([
            'success' => true,
            'data' => $analysis
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function analyze_keywords($data) {
    try {
        $content = $data['content'] ?? '';
        $focus_keyword = $data['focus_keyword'] ?? '';
        $meta_desc = $data['meta_description'] ?? '';
        $title = $data['title'] ?? '';
        
        if (empty($content) || empty($focus_keyword)) {
            echo json_encode(['success' => false, 'message' => 'Content and keyword required']);
            return;
        }
        
        $analysis = KeywordOptimizer::analyzeKeywords($content, $focus_keyword, $meta_desc, $title);
        
        echo json_encode([
            'success' => true,
            'data' => $analysis
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function get_analytics_data($data) {
    global $analytics;
    
    try {
        $days = $data['days'] ?? 30;
        $report = $analytics->generateReport($days);
        
        echo json_encode([
            'success' => true,
            'data' => $report
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function generate_schema_ajax($data) {
    try {
        require_once 'seo_schema_generator.php';
        $type = $data['schema_type'] ?? '';
        $schema = SchemaMarkupGenerator::generateSchema($type, $data);
        
        if (is_string($schema)) {
            $schemaJson = $schema;
        } else {
            $schemaJson = json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        }
        
        echo json_encode([
            'success' => true,
            'schema' => $schemaJson
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function audit_page_handler($data) {
    try {
        global $db_config;
        
        $url = filter_var($data['audit_url'] ?? '', FILTER_VALIDATE_URL);
        
        if (!$url) {
            echo json_encode(['success' => false, 'message' => 'Invalid URL provided']);
            return;
        }
        
        $db = new mysqli(
            $db_config['host'],
            $db_config['user'],
            $db_config['password'],
            $db_config['database']
        );
        
        $auditor = new SiteAuditor($url, $db);
        $result = $auditor->auditPage();
        
        echo json_encode($result);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function analyze_content_handler($data) {
    try {
        $content = $data['content'] ?? '';
        $focus_keyword = $data['focus_keyword'] ?? '';
        $title = $data['title'] ?? '';
        $meta_description = $data['meta_description'] ?? '';
        
        $analysis = [];
        
        if (!empty($content)) {
            $analysis['readability'] = ReadabilityAnalyzer::analyze($content);
        }
        
        if (!empty($focus_keyword)) {
            $analysis['keywords'] = KeywordOptimizer::analyzeKeywords(
                $content,
                $focus_keyword,
                $meta_description,
                $title
            );
        }
        
        echo json_encode([
            'success' => true,
            'analysis' => $analysis
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

function analyze_yoast_seo($data) {
    try {
        $analyzer = new YoastSEOAnalyzer([
            'content' => $data['content'] ?? '',
            'title' => $data['title'] ?? '',
            'meta_description' => $data['meta_description'] ?? '',
            'focus_keyword' => $data['focus_keyword'] ?? '',
            'slug' => $data['slug'] ?? '',
            'url' => $data['url'] ?? ''
        ]);
        
        $analysis = $analyzer->analyze();
        
        echo json_encode([
            'success' => true,
            'analysis' => $analysis
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

function suggest_internal_links($data) {
    global $db;
    
    try {
        $keyword = strtolower($data['keyword'] ?? '');
        $itemType = $data['item_type'] ?? 'product';
        
        if (empty($keyword)) {
            echo json_encode(['success' => false, 'message' => 'Keyword required']);
            exit;
        }
        
        $links = [];
        
        // Search products
        if ($itemType === 'product') {
            $query = "SELECT id, title FROM products WHERE LOWER(title) LIKE ? OR LOWER(description) LIKE ? LIMIT 5";
        } else {
            $query = "SELECT id, title FROM blogs WHERE LOWER(title) LIKE ? OR LOWER(content) LIKE ? LIMIT 5";
        }
        
        $stmt = $db->prepare($query);
        $searchTerm = "%{$keyword}%";
        $stmt->bind_param("ss", $searchTerm, $searchTerm);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            if ($itemType === 'product') {
                $links[] = [
                    'text' => $row['title'],
                    'url' => '/product.php?id=' . $row['id']
                ];
            } else {
                $links[] = [
                    'text' => $row['title'],
                    'url' => '/blog.php?id=' . $row['id']
                ];
            }
        }
        
        // Also search categories
        $catQuery = "SELECT id, name FROM categories WHERE LOWER(name) LIKE ? LIMIT 3";
        $catStmt = $db->prepare($catQuery);
        $catStmt->bind_param("s", $searchTerm);
        $catStmt->execute();
        $catResult = $catStmt->get_result();
        
        while ($catRow = $catResult->fetch_assoc()) {
            $links[] = [
                'text' => $catRow['name'] . ' Category',
                'url' => '/category.php?id=' . $catRow['id']
            ];
        }
        
        echo json_encode([
            'success' => true,
            'links' => $links
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

function bulk_apply_seo($data) {
    global $db, $seo_plugin;
    
    try {
        // Load the schema generator class once at the beginning
        require_once 'seo_schema_generator.php';
        
        $itemType = $data['item_type'] ?? 'product';
        $autoGenerate = $data['auto_generate'] ?? true;
        
        $processed = 0;
        $errors = [];
        
        if ($itemType === 'product') {
            $json_file = __DIR__ . '/data/products.json';
            if (!file_exists($json_file)) {
                throw new Exception("Products file not found");
            }
            
            $products_json = file_get_contents($json_file);
            if (!$products_json) {
                throw new Exception("Could not read products file");
            }
            
            $products = json_decode($products_json, true);
            if (!is_array($products)) {
                throw new Exception("Invalid products JSON format");
            }
            
            foreach ($products as $product) {
                try {
                    // Validate product has required fields
                    if (!isset($product['id'])) {
                        $errors[] = "Product missing id field";
                        continue;
                    }
                    
                    $title = $product['title'] ?? 'Product';
                    $description = $product['desc'] ?? '';
                    
                    // Generate SEO data
                    $seoTitle = $autoGenerate ? substr($title, 0, 60) : '';
                    $seoDesc = $autoGenerate ? substr($description, 0, 160) : '';
                    $focusKeyword = $autoGenerate ? strtolower(explode(' ', $title)[0] ?? '') : '';
                    $slug = $autoGenerate ? strtolower(preg_replace('/[^a-z0-9]+/', '-', $title)) : '';
                    
                    // Generate schema
                    $schema = SchemaMarkupGenerator::generateSchema('product', [
                        'name' => $title,
                        'description' => $description,
                        'price' => $product['price'] ?? 0,
                        'url' => '/product.php?id=' . $product['id']
                    ]);
                    
                    // Ensure schema is a string (it should already be JSON from generateSchema)
                    if (!is_string($schema)) {
                        $schema = json_encode($schema);
                    }
                    
                    $result = $seo_plugin->saveSEOData('product', $product['id'], [
                        'title' => $seoTitle,
                        'meta_description' => $seoDesc,
                        'focus_keyword' => $focusKeyword,
                        'slug' => $slug,
                        'schema_markup' => $schema
                    ]);
                    
                    if ($result) {
                        $processed++;
                    } else {
                        $errors[] = "Product ID {$product['id']}: Failed to save SEO data";
                    }
                } catch (Exception $e) {
                    $errors[] = "Product ID {$product['id']}: " . $e->getMessage();
                }
            }
        } elseif ($itemType === 'blog') {
            $query = "SELECT id, title, content FROM blogs";
            $result = $db->query($query);
            
            if (!$result) {
                throw new Exception("Database query failed: " . $db->error);
            }
            
            while ($blog = $result->fetch_assoc()) {
                try {
                    // Validate blog has required fields
                    if (!isset($blog['id'])) {
                        $errors[] = "Blog missing id field";
                        continue;
                    }
                    
                    $title = $blog['title'] ?? 'Blog Post';
                    $content = strip_tags($blog['content'] ?? '');
                    $description = substr($content, 0, 160);
                    
                    $seoTitle = $autoGenerate ? substr($title, 0, 60) : '';
                    $seoDesc = $autoGenerate ? $description : '';
                    $focusKeyword = $autoGenerate ? strtolower(explode(' ', $title)[0] ?? '') : '';
                    $slug = $autoGenerate ? strtolower(preg_replace('/[^a-z0-9]+/', '-', $title)) : '';
                    
                    $schema = SchemaMarkupGenerator::generateSchema('blog', [
                        'title' => $title,
                        'description' => $description,
                        'url' => '/blog.php?id=' . $blog['id']
                    ]);
                    
                    // Ensure schema is a string (it should already be JSON from generateSchema)
                    if (!is_string($schema)) {
                        $schema = json_encode($schema);
                    }
                    
                    $result = $seo_plugin->saveSEOData('blog', $blog['id'], [
                        'title' => $seoTitle,
                        'meta_description' => $seoDesc,
                        'focus_keyword' => $focusKeyword,
                        'slug' => $slug,
                        'schema_markup' => $schema
                    ]);
                    
                    if ($result) {
                        $processed++;
                    } else {
                        $errors[] = "Blog ID {$blog['id']}: Failed to save SEO data";
                    }
                } catch (Exception $e) {
                    $errors[] = "Blog ID {$blog['id']}: " . $e->getMessage();
                }
            }
        } else {
            throw new Exception("Invalid item type: $itemType");
        }
        
        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'processed' => $processed,
            'errors' => $errors,
            'message' => "Successfully applied SEO to {$processed} items"
        ]);
    } catch (Exception $e) {
        // Ensure we're returning JSON even on error
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage(),
            'processed' => 0,
            'errors' => []
        ]);
    }
    exit;
}

// Load Products via AJAX - Load from JSON file
function load_products_ajax($data) {
    global $db;
    
    try {
        error_log("DEBUG: Starting load_products_ajax");
        // Load products from JSON file
        $json_file = __DIR__ . '/data/products.json';
        
        if (!file_exists($json_file)) {
            throw new Exception("Products file not found at: $json_file");
        }
        
        $json_content = file_get_contents($json_file);
        $products_raw = json_decode($json_content, true);
        
        if (!is_array($products_raw)) {
            throw new Exception("Invalid products data format");
        }
        
        error_log("DEBUG: Found " . count($products_raw) . " products in JSON");
        
        $products = [];
        foreach ($products_raw as $prod) {
            // Get SEO data if it exists
            $seo_data = null;
            $seo_query = "SELECT * FROM seo_settings WHERE page_type='product' AND page_id=" . intval($prod['id']);
            $seo_result = $db->query($seo_query);
            if ($seo_result) {
                $seo_data = $seo_result->fetch_assoc();
            }
            
            $desc = isset($prod['desc']) ? $prod['desc'] : '';
            if (strlen($desc) > 100) {
                $desc = substr($desc, 0, 100) . '...';
            }
            
            $products[] = [
                'id' => $prod['id'],
                'title' => $prod['title'] ?? 'Unknown',
                'description' => $desc,
                'price' => $prod['price'] ?? 0,
                'seo_score' => $seo_data ? 75 : 0,
                'has_seo' => $seo_data ? true : false,
                'seo_title' => $seo_data['title'] ?? 'Not set',
                'meta_description' => $seo_data['meta_description'] ?? 'Not set'
            ];
        }
        
        error_log("DEBUG: Processed " . count($products) . " products for display");
        
        echo json_encode([
            'success' => true,
            'products' => $products,
            'count' => count($products),
            'total' => count($products)
        ]);
    } catch (Exception $e) {
        error_log("ERROR in load_products_ajax: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage(),
            'error' => 'Failed to load products: ' . $e->getMessage()
        ]);
    }
    exit;
}

// Load Blogs via AJAX
function load_blogs_ajax($data) {
    global $db;
    
    try {
        error_log("DEBUG: Starting load_blogs_ajax");
        
        $query = "SELECT id, title, content FROM blogs ORDER BY id DESC LIMIT 100";
        error_log("DEBUG: Query = $query");
        
        $result = $db->query($query);
        
        if (!$result) {
            error_log("DEBUG: Query failed - " . $db->error);
            throw new Exception("Query failed: " . $db->error);
        }
        
        $blogs = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $seo_query = "SELECT * FROM seo_settings WHERE page_type='blog' AND page_id=" . intval($row['id']);
                $seo_result = $db->query($seo_query);
                $seo_data = $seo_result ? $seo_result->fetch_assoc() : null;
                
                $excerpt = isset($row['content']) ? $row['content'] : '';
                if (strlen($excerpt) > 100) {
                    $excerpt = substr($excerpt, 0, 100) . '...';
                }
                
                $blogs[] = [
                    'id' => $row['id'],
                    'title' => $row['title'],
                    'excerpt' => $excerpt,
                    'seo_score' => $seo_data ? 75 : 0,
                    'has_seo' => $seo_data ? true : false,
                    'seo_title' => $seo_data['title'] ?? 'Not set',
                    'meta_description' => $seo_data['meta_description'] ?? 'Not set'
                ];
            }
        }
        
        error_log("DEBUG: Found " . count($blogs) . " blogs");
        
        echo json_encode([
            'success' => true,
            'blogs' => $blogs,
            'count' => count($blogs),
            'total' => count($blogs)
        ]);
    } catch (Exception $e) {
        error_log("ERROR in load_blogs_ajax: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage(),
            'error' => 'Failed to load blogs: ' . $e->getMessage()
        ]);
    }
    exit;
}


// Load Categories via AJAX
function load_categories_ajax($data) {
    global $db;
    
    try {
        // Load categories from JSON file (same as products)
        $json_file = __DIR__ . '/data/categories.json';
        
        if (!file_exists($json_file)) {
            throw new Exception("Categories file not found");
        }
        
        $json_content = file_get_contents($json_file);
        $categories_raw = json_decode($json_content, true);
        
        if (!is_array($categories_raw)) {
            throw new Exception("Invalid categories data format");
        }
        
        $categories = [];
        foreach ($categories_raw as $cat) {
            // Get SEO data if it exists
            $seo_data = null;
            $seo_query = "SELECT * FROM seo_settings WHERE page_type='category' AND page_id=" . intval($cat['id']);
            $seo_result = $db->query($seo_query);
            if ($seo_result) {
                $seo_data = $seo_result->fetch_assoc();
            }
            
            // Calculate SEO score
            $seo_score = 0;
            if ($seo_data) {
                $score_data = [
                    'title' => $seo_data['title'] ?? '',
                    'meta_description' => $seo_data['meta_description'] ?? '',
                    'focus_keyword' => $seo_data['focus_keyword'] ?? '',
                    'slug' => $seo_data['slug'] ?? '',
                    'schema_markup' => $seo_data['schema_markup'] ?? '',
                    'og_title' => $seo_data['og_title'] ?? '',
                    'og_description' => $seo_data['og_description'] ?? '',
                    'content' => $cat['description'] ?? ''
                ];
                $seo_score = SEOHelper::calculateSEOScore($score_data);
            }
            
            $categories[] = [
                'id' => $cat['id'],
                'name' => $cat['name'] ?? 'Unknown',
                'has_seo' => $seo_data ? true : false,
                'seo_score' => $seo_score,
                'seo_title' => $seo_data['title'] ?? 'Not set',
                'meta_description' => $seo_data['meta_description'] ?? 'Not set'
            ];
        }
        
        echo json_encode([
            'success' => true,
            'categories' => $categories,
            'count' => count($categories)
        ]);
    } catch (Exception $e) {
        error_log("ERROR in load_categories_ajax: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
    exit;
}

// Save Product SEO
function save_product_seo($data) {
    global $seo_plugin;
    
    try {
        $result = $seo_plugin->saveSEOData(
            'product',
            $data['product_id'] ?? 0,
            $data
        );
        
        echo json_encode([
            'success' => $result,
            'message' => $result ? 'Product SEO saved successfully' : 'Error saving product SEO'
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// Save Blog SEO
function save_blog_seo($data) {
    global $seo_plugin;
    
    try {
        $result = $seo_plugin->saveSEOData(
            'blog',
            $data['blog_id'] ?? 0,
            $data
        );
        
        echo json_encode([
            'success' => $result,
            'message' => $result ? 'Blog SEO saved successfully' : 'Error saving blog SEO'
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// Ensure SEO tables exist
function ensure_seo_tables_exist($db) {
    // Create seo_settings table (matches SEOPlugin class)
    $sql_seo = "CREATE TABLE IF NOT EXISTS `seo_settings` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `page_type` VARCHAR(50) NOT NULL,
        `page_id` INT NOT NULL,
        `title` VARCHAR(255),
        `meta_description` TEXT,
        `meta_keywords` VARCHAR(255),
        `focus_keyword` VARCHAR(100),
        `slug` VARCHAR(255),
        `canonical_url` VARCHAR(500),
        `robots_meta` VARCHAR(100) DEFAULT 'index, follow',
        `og_title` VARCHAR(255),
        `og_description` VARCHAR(255),
        `og_image` VARCHAR(500),
        `twitter_title` VARCHAR(255),
        `twitter_description` VARCHAR(255),
        `twitter_image` VARCHAR(500),
        `readability_score` INT DEFAULT 0,
        `keyword_density` FLOAT DEFAULT 0,
        `keyword_rank` INT,
        `schema_markup` LONGTEXT,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY `unique_page` (`page_type`, `page_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if (!$db->query($sql_seo)) {
        // Table might already exist, ignore error
    }
    
    // Create seo_analytics table if needed
    $sql_analytics = "CREATE TABLE IF NOT EXISTS `seo_analytics` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `seo_id` INT NOT NULL,
        `page_type` VARCHAR(50),
        `impressions` INT DEFAULT 0,
        `clicks` INT DEFAULT 0,
        `ctr` FLOAT DEFAULT 0,
        `position` INT DEFAULT 0,
        `date` DATE,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY `unique_analytics` (`seo_id`, `date`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if (!$db->query($sql_analytics)) {
        // Table might already exist, ignore error
    }
}

// Start output buffering for page HTML
ob_start();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="styles.css" rel="stylesheet">
    <title>SEO Management - Admin Panel</title>
    <script src="seo_analyzer.js"></script>
    <script src="seo_snippet_preview.js"></script>
    <script src="seo_health_check.js"></script>
    <script src="js/yoast_seo_ui.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: #f8f9fa;
            color: #333;
        }
        
        .seo-container {
            display: flex;
            min-height: 100vh;
        }
        
        .seo-sidebar {
            width: 280px;
            background: #431e3d;
            color: #fff;
            padding: 30px 0;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        
        .seo-sidebar-header {
            padding: 0 20px 30px;
            border-bottom: 1px solid rgba(218, 79, 121, 0.1);
            margin-bottom: 20px;
        }
        
        .seo-sidebar-header h2 {
            font-size: 18px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .seo-sidebar-menu {
            list-style: none;
        }
        
        .seo-sidebar-menu li {
            margin-bottom: 0;
        }
        
        .seo-sidebar-menu a {
            display: block;
            padding: 12px 20px;
            color: #ecf0f1;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 4px solid transparent;
            font-size: 14px;
            font-weight: 500;
        }
        
        .seo-sidebar-menu a:hover {
            background: rgba(213, 97, 140, 0.1);
            border-left-color: #cb6a93;
        }
        
        .seo-sidebar-menu a.active {
            background: #d16baf;
            border-left-color: #d16bad;
            color: #fff;
        }
        
        .seo-main {
            margin-left: 280px;
            flex: 1;
            padding: 40px;
        }
        
        .seo-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 40px;
        }
        
        .seo-header h1 {
            font-size: 32px;
            font-weight: 700;
            color: #2c3e50;
        }
        
        .seo-actions {
            display: flex;
            gap: 12px;
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: #df7caa;
            color: #fff;
        }
        
        .btn-primary:hover {
            background: #ab4070;
        }
        
        .btn-success {
            background: #a53467;
            color: #fff;
        }
        
        .btn-success:hover {
            background: #f291b3;
        }
        
        .btn-secondary {
            background: #95a5a6;
            color: #fff;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .grid-2 {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 30px;
            margin-bottom: 40px;
        }
        
        .card {
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            border-top: 4px solid #e26db9;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 20px;
            color: #c55e7f;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #e1649c;
            font-size: 14px;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #f584c8;
            box-shadow: 0 0 0 3px rgba(220, 136, 196, 0.1);
        }
        
        .char-count {
            font-size: 12px;
            color: #db679d;
            margin-top: 4px;
        }
        
        .char-count.warning {
            color: #f176a7;
        }
        
        .seo-score {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .seo-score-circle {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 28px;
            color: #fff;
        }
        
        .seo-score-circle.excellent {
            background: #ce7ebf;
        }
        
        .seo-score-circle.good {
            background: #b06e9f;
        }
        
        .seo-score-circle.warning {
            background: #e74c3c;
        }
        
        .seo-score-info h3 {
            font-size: 16px;
            margin-bottom: 4px;
        }
        
        .seo-score-info p {
            font-size: 14px;
            color: #7f8c8d;
        }
        
        .tabs {
            display: flex;
            gap: 0;
            margin-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
        }
        
        .tab-btn {
            padding: 12px 20px;
            background: none;
            border: none;
            cursor: pointer;
            font-weight: 600;
            color: #f09fcc;
            font-size: 14px;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
        }
        
        .tab-btn.active {
            color: #e186b1;
            border-bottom-color: #e098ca;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .suggestion-item {
            padding: 15px;
            background: #f8f9fa;
            border-left: 4px solid #dc8fa6;
            margin-bottom: 12px;
            border-radius: 4px;
        }
        
        .suggestion-item.info {
            border-left-color: #9c618b;
        }
        
        .suggestion-item.success {
            border-left-color: #f7caf4;
        }
        
        .suggestion-item.warning {
            border-left-color: #eaadce;
        }
        
        .suggestion-item-title {
            font-weight: 600;
            color: #d6a0c7;
            font-size: 14px;
        }
        
        .suggestion-item-message {
            font-size: 13px;
            color: #7f8c8d;
            margin-top: 4px;
        }
        
        .metric-box {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .metric-label {
            font-size: 13px;
            color: #ee94e3;
            font-weight: 600;
            text-transform: uppercase;
            margin-bottom: 8px;
        }
        
        .metric-value {
            font-size: 24px;
            font-weight: 700;
            color: #b990b7;
        }
        
        .metric-change {
            font-size: 12px;
            margin-top: 6px;
        }
        
        .metric-change.positive {
            color: #e799ce;
        }
        
        .metric-change.negative {
            color: #bd7ea4;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 30px;
        }
        
        .loading.active {
            display: block;
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #ee85d0;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .analytics-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .analytics-card {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            text-align: center;
        }
        
        .analytics-card-icon {
            font-size: 32px;
            margin-bottom: 12px;
        }
        
        .analytics-card-value {
            font-size: 28px;
            font-weight: 700;
            color: #f33ca7;
            margin-bottom: 4px;
        }
        
        .analytics-card-label {
            font-size: 12px;
            color: #7f8c8d;
            text-transform: uppercase;
            font-weight: 600;
        }
        
        .full-width {
            grid-column: 1 / -1;
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        table th {
            background: #f8f9fa;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            font-size: 13px;
            color: #7f8c8d;
            text-transform: uppercase;
            border-bottom: 1px solid #e9ecef;
        }
        
        table td {
            padding: 12px;
            border-bottom: 1px solid #e9ecef;
            font-size: 14px;
        }
        
        table tr:hover {
            background: #f8f9fa;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-success {
            background: #d4edda;
            color: #ecb0c5;
        }
        
        .badge-warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .badge-danger {
            background: #f8d7da;
            color: #721c24;
        }
        
        @media (max-width: 768px) {
            .seo-sidebar {
                width: 100%;
                position: relative;
                height: auto;
            }
            
            .seo-main {
                margin-left: 0;
                padding: 20px;
            }
            
            .grid-2 {
                grid-template-columns: 1fr;
            }
            
            .analytics-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        /* Yoast-Style SEO UI */
        .yoast-seo-panel {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 20px 0;
        }
        
        .yoast-seo-header {
            display: flex;
            align-items: center;
            gap: 20px;
            padding: 20px;
            border-bottom: 1px solid #eee;
            background: #f8f9fa;
        }
        
        .yoast-seo-score, .yoast-readability-score {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .score-circle, .readability-circle {
            position: relative;
        }
        
        .score-label, .readability-label {
            display: flex;
            flex-direction: column;
        }
        
        .status-badge {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-badge.status-good {
            background: #d4edda;
            color: #155724;
        }
        
        .status-badge.status-warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-badge.status-bad {
            background: #f8d7da;
            color: #721c24;
        }
        
        .score-type {
            font-size: 11px;
            color: #666;
            margin-top: 4px;
        }
        
        .yoast-seo-content {
            padding: 0;
        }
        
        .yoast-section {
            border-bottom: 1px solid #eee;
            padding: 15px 20px;
        }
        
        .yoast-section:last-child {
            border-bottom: none;
        }
        
        .yoast-section.status-good {
            background: #f8fff9;
        }
        
        .yoast-section.status-warning {
            background: #fffef8;
        }
        
        .yoast-section.status-bad {
            background: #fff8f8;
        }
        
        .yoast-section-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .yoast-icon {
            font-size: 18px;
        }
        
        .yoast-title {
            font-weight: 600;
            font-size: 14px;
            color: #333;
        }
        
        .yoast-section-content {
            margin-left: 28px;
        }
        
        .yoast-message {
            color: #666;
            font-size: 13px;
            margin: 0;
        }
        
        .yoast-good, .yoast-issues {
            list-style: none;
            padding: 0;
            margin: 8px 0;
        }
        
        .yoast-good li {
            color: #155724;
            font-size: 13px;
            padding: 4px 0;
            padding-left: 20px;
            position: relative;
        }
        
        .yoast-good li:before {
            content: '✓';
            position: absolute;
            left: 0;
            color: #28a745;
            font-weight: bold;
        }
        
        .yoast-issues li {
            color: #721c24;
            font-size: 13px;
            padding: 4px 0;
            padding-left: 20px;
            position: relative;
        }
        
        .yoast-issues li:before {
            content: '✗';
            position: absolute;
            left: 0;
            color: #dc3545;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="seo-container">
        <!-- Sidebar -->
        <aside class="seo-sidebar">
            <div class="seo-sidebar-header">
                <h2> SEO Manager</h2>
            </div>
            <ul class="seo-sidebar-menu">
                <li><a href="?action=dashboard" class="<?php echo $action === 'dashboard' ? 'active' : ''; ?>">Dashboard</a></li>
                <li style="padding-top: 8px; border-top: 1px solid rgba(218, 79, 121, 0.2); margin-top: 8px; margin-bottom: 8px;"><strong style="font-size: 11px; padding: 0 20px; display: block; color: #cb6a93; text-transform: uppercase; letter-spacing: 1px;">Pages & Content</strong></li>
                <li><a href="?action=pages" class="<?php echo $action === 'pages' ? 'active' : ''; ?>">📄 Pages & Posts</a></li>
                <li><a href="?action=seo-products" class="<?php echo $action === 'seo-products' ? 'active' : ''; ?>">🛍️ Products SEO</a></li>
                <li><a href="?action=seo-blogs" class="<?php echo $action === 'seo-blogs' ? 'active' : ''; ?>">📝 Blogs SEO</a></li>
                <li><a href="?action=seo-categories" class="<?php echo $action === 'seo-categories' ? 'active' : ''; ?>">📂 Categories</a></li>
                <li><a href="?action=seo-homepage" class="<?php echo $action === 'seo-homepage' ? 'active' : ''; ?>">🏠 Homepage</a></li>
                <li><a href="?action=seo-about" class="<?php echo $action === 'seo-about' ? 'active' : ''; ?>">ℹ️ About Page</a></li>
                <li><a href="?action=seo-contact" class="<?php echo $action === 'seo-contact' ? 'active' : ''; ?>">📧 Contact Page</a></li>
                <li style="padding-top: 8px; border-top: 1px solid rgba(218, 79, 121, 0.2); margin-top: 8px; margin-bottom: 8px;"><strong style="font-size: 11px; padding: 0 20px; display: block; color: #cb6a93; text-transform: uppercase; letter-spacing: 1px;">Analysis Tools</strong></li>
                <li><a href="?action=meta-tags" class="<?php echo $action === 'meta-tags' ? 'active' : ''; ?>">🏷️ Meta Tags</a></li>
                <li><a href="?action=readability" class="<?php echo $action === 'readability' ? 'active' : ''; ?>">📊 Readability</a></li>
                <li><a href="?action=keywords" class="<?php echo $action === 'keywords' ? 'active' : ''; ?>">🔍 Keywords</a></li>
                <li><a href="?action=schema" class="<?php echo $action === 'schema' ? 'active' : ''; ?>">⚙️ Schema Markup</a></li>
                <li style="padding-top: 8px; border-top: 1px solid rgba(218, 79, 121, 0.2); margin-top: 8px; margin-bottom: 8px;"><strong style="font-size: 11px; padding: 0 20px; display: block; color: #cb6a93; text-transform: uppercase; letter-spacing: 1px;">Monitoring</strong></li>
                <li><a href="?action=analytics" class="<?php echo $action === 'analytics' ? 'active' : ''; ?>">📈 Analytics</a></li>
                <li><a href="?action=social-tags" class="<?php echo $action === 'social-tags' ? 'active' : ''; ?>">👥 Social Media Tags</a></li>
                <li style="padding-top: 8px; border-top: 1px solid rgba(218, 79, 121, 0.2); margin-top: 8px; margin-bottom: 8px;"><strong style="font-size: 11px; padding: 0 20px; display: block; color: #cb6a93; text-transform: uppercase; letter-spacing: 1px;">Configuration</strong></li>
                <li><a href="?action=settings" class="<?php echo $action === 'settings' ? 'active' : ''; ?>">⚡ Settings</a></li>
            </ul>
        </aside>
        
        <!-- Main Content -->
        <main class="seo-main">
            <div class="seo-header">
                <h1><?php echo get_page_title($action); ?></h1>
                <div class="seo-actions">
                    <!-- <button class="btn btn-success" onclick="exportData()"> Export</button> -->
                    <button class="btn btn-secondary" onclick="window.history.back()">← Back</button>
                    <a href="admin_dashboard.php" class="back-btn" style="background:#F07E2D; color:#fff; text-decoration:none; padding:8px 12px; border-radius:6px;" > Back to Dashboard</a>
                </div>
            </div>
            
            <?php
            // Render content based on action
            switch ($action) {
                case 'dashboard':
                    render_dashboard();
                    break;
                case 'pages':
                    render_pages();
                    break;
                case 'meta-tags':
                    render_meta_tags();
                    break;
                case 'readability':
                    render_readability();
                    break;
                case 'keywords':
                    render_keywords();
                    break;
                case 'schema':
                    render_schema();
                    break;
                case 'analytics':
                    render_analytics();
                    break;
                case 'social-tags':
                    render_social_tags();
                    break;
                case 'seo-products':
                    render_seo_products();
                    break;
                case 'seo-blogs':
                    render_seo_blogs();
                    break;
                case 'seo-categories':
                    render_seo_categories();
                    break;
                case 'seo-homepage':
                    render_seo_homepage();
                    break;
                case 'seo-about':
                    render_seo_about();
                    break;
                case 'seo-contact':
                    render_seo_contact();
                    break;
                case 'settings':
                    render_settings();
                    break;
                default:
                    render_dashboard();
            }
            ?>
        </main>
    </div>
    
    <script>
        // Global SEO Analyzer
        const analyzer = new SEOContentAnalyzer();
        
        // Tab Management
        function showTab(tabName) {
            const tabs = document.querySelectorAll('.tab-content');
            tabs.forEach(tab => tab.classList.remove('active'));
            document.getElementById(tabName)?.classList.add('active');
            const btns = document.querySelectorAll('.tab-btn');
            btns.forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');
        }
        
        // Readability Analysis
        function analyzeReadability() {
            const contentInput = document.getElementById('content');
            const content = contentInput ? contentInput.value : '';
            
            if (!content) {
                showNotification('Please add content to analyze', 'error');
                return;
            }
            
            const loading = document.querySelector('.loading');
            if (loading) loading.classList.add('active');
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=analyze_readability&content=' + encodeURIComponent(content)
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    displayReadabilityResults(data.data);
                } else {
                    showNotification(data.message || 'Analysis failed', 'error');
                }
                if (loading) loading.classList.remove('active');
            })
            .catch(err => {
                console.error(err);
                showNotification('Error analyzing content', 'error');
                if (loading) loading.classList.remove('active');
            });
        }
        
        function displayReadabilityResults(data) {
            const resultsDiv = document.getElementById('readabilityResults');
            if (!resultsDiv) return;
            
            let html = `
                <div class="seo-score">
                    <div class="seo-score-circle ${getScoreClass(data.score)}">
                        ${data.score}
                    </div>
                    <div class="seo-score-info">
                        <h3>${data.grade_description}</h3>
                        <p>Flesch Reading Ease: ${data.flesch_reading_ease}</p>
                        <p>Grade Level: ${data.flesch_kincaid_grade}</p>
                    </div>
                </div>
            `;
            
            if (data.suggestions && data.suggestions.length > 0) {
                html += '<div class="card" style="margin-top: 20px;"><div class="card-title">Suggestions</div>';
                data.suggestions.forEach(s => {
                    const priorityClass = s.priority || 'info';
                    html += `
                        <div class="suggestion-item ${priorityClass}">
                            <div class="suggestion-item-title">${s.suggestion}</div>
                            <div class="suggestion-item-message">${s.action}</div>
                        </div>
                    `;
                });
                html += '</div>';
            }
            
            resultsDiv.innerHTML = html;
        }
        
        // Keyword Analysis
        function analyzeKeywords() {
            const focusKeywordInput = document.getElementById('focusKeyword');
            const contentInput = document.getElementById('keywordContent');
            
            const focusKeyword = focusKeywordInput ? focusKeywordInput.value : '';
            const content = contentInput ? contentInput.value : '';
            
            if (!focusKeyword || !content) {
                showNotification('Please enter both keyword and content', 'error');
                return;
            }
            
            const loading = document.querySelector('.loading');
            if (loading) loading.classList.add('active');
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=analyze_keywords&focus_keyword=' + encodeURIComponent(focusKeyword) + 
                      '&content=' + encodeURIComponent(content)
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    displayKeywordResults(data.data);
                } else {
                    showNotification(data.message || 'Analysis failed', 'error');
                }
                if (loading) loading.classList.remove('active');
            })
            .catch(err => {
                console.error(err);
                showNotification('Error analyzing keywords', 'error');
                if (loading) loading.classList.remove('active');
            });
        }
        
        function displayKeywordResults(data) {
            const resultsDiv = document.getElementById('keywordResults');
            if (!resultsDiv) return;
            
            // Extract data from focus_analysis if available
            const focusData = data.focus_analysis || {};
            const density = focusData.density !== undefined ? focusData.density : 0;
            const count = focusData.count !== undefined ? focusData.count : 0;
            const score = data.score || 0;
            
            let html = `
                <div class="seo-score">
                    <div class="seo-score-circle ${getScoreClass(score)}">
                        ${score}
                    </div>
                    <div class="seo-score-info">
                        <h3>Keyword Analysis</h3>
                        <p>Density: ${density}%</p>
                        <p>Count: ${count}</p>
                    </div>
                </div>
            `;
            
            if (data.suggestions && data.suggestions.length > 0) {
                data.suggestions.forEach(s => {
                    const priorityClass = s.priority || 'info';
                    html += `
                        <div class="suggestion-item ${priorityClass}">
                            <div class="suggestion-item-title">${s.suggestion}</div>
                            <div class="suggestion-item-message">${s.action || ''}</div>
                        </div>
                    `;
                });
            }
            
            resultsDiv.innerHTML = html;
        }
        
        // SEO Data Saving
        function saveSEOData() {
            const formData = new FormData(document.getElementById('seoForm'));
            formData.append('action', 'save_seo');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showNotification('SEO data saved successfully!', 'success');
                } else {
                    showNotification(data.message || 'Error saving SEO data', 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showNotification('Error saving data', 'error');
            });
            
            return false;
        }
        
        // Analytics Data
        function loadAnalytics() {
            const loading = document.querySelector('.loading');
            if (loading) loading.classList.add('active');
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=get_analytics&days=30'
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    displayAnalytics(data.data);
                } else {
                    showNotification(data.message || 'Error loading analytics', 'error');
                }
                if (loading) loading.classList.remove('active');
            })
            .catch(err => {
                console.error(err);
                showNotification('Error loading analytics', 'error');
                if (loading) loading.classList.remove('active');
            });
        }
        
        function displayAnalytics(data) {
            console.log('Analytics data:', data);
        }
        
        // Save Social Tags (OG & Twitter)
        function saveSocialTags() {
            const formData = new FormData(document.getElementById('socialTagsForm'));
            formData.append('action', 'save_seo');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showNotification('Social media tags saved successfully!', 'success');
                } else {
                    showNotification(data.message || 'Error saving social tags', 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showNotification('Error saving social tags', 'error');
            });
            
            return false;
        }
        
        // Save Page SEO (Generic function for all pages)
        function savePageSEO(pageType, pageId) {
            const formId = pageType + 'SEOForm';
            const form = document.getElementById(formId);
            
            if (!form) {
                showNotification('Form not found', 'error');
                return false;
            }
            
            const formData = new FormData(form);
            formData.append('action', 'save_seo');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showNotification(pageType + ' SEO saved successfully!', 'success');
                } else {
                    showNotification(data.message || 'Error saving SEO data', 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showNotification('Error saving SEO data', 'error');
            });
            
            return false;
        }
        
        // Schema Generation
        function generateSchema() {
            const schemaTypeInput = document.getElementById('schemaType');
            const titleInput = document.getElementById('schemaTitle');
            const descInput = document.getElementById('schemaDescription');
            
            const schemaType = schemaTypeInput ? schemaTypeInput.value : 'article';
            const title = titleInput ? titleInput.value : '';
            const description = descInput ? descInput.value : '';
            
            const payload = {
                action: 'generate_schema',
                schema_type: schemaType,
                title: title,
                description: description
            };
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams(payload).toString()
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    displaySchemaOutput(data.schema);
                } else {
                    showNotification(data.message || 'Error generating schema', 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showNotification('Error generating schema', 'error');
            });
        }
        
        function displaySchemaOutput(schema) {
            const outputDiv = document.getElementById('schemaOutput');
            if (!outputDiv) return;
            
            outputDiv.innerHTML = `
                <div class="card">
                    <div class="card-title">Generated Schema</div>
                    <pre style="background: #f8f9fa; padding: 15px; border-radius: 6px; overflow-x: auto;">
${schema}
                    </pre>
                    <button type="button" class="btn btn-primary" onclick="copySchema()"> Copy</button>
                </div>
            `;
        }
        
        function copySchema() {
            const text = document.querySelector('#schemaOutput pre')?.textContent || '';
            navigator.clipboard.writeText(text).then(() => {
                showNotification('Schema copied to clipboard!', 'success');
            });
        }
        
        // Page Audit
        function auditPage() {
            const url = prompt('Enter the URL to audit:');
            if (!url) return;
            
            const loading = document.querySelector('.loading');
            if (loading) loading.classList.add('active');
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=audit_page&audit_url=' + encodeURIComponent(url)
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    displayAuditResults(data.audit);
                } else {
                    showNotification(data.message || 'Audit failed', 'error');
                }
                if (loading) loading.classList.remove('active');
            })
            .catch(err => {
                console.error(err);
                showNotification('Error running audit', 'error');
                if (loading) loading.classList.remove('active');
            });
        }
        
        function displayAuditResults(audit) {
            let html = `<div class="card">
                <div class="card-title">Site Audit Report</div>
                <div style="margin-bottom: 20px;">
                    <h4>Overall Score: ${audit.summary.overall_score}/100 (${audit.summary.grade})</h4>
                </div>`;
            
            Object.entries(audit.checks).forEach(([key, check]) => {
                const colorClass = check.severity || 'info';
                html += `
                    <div class="suggestion-item ${colorClass}">
                        <div class="suggestion-item-title">${check.message}</div>
                        ${check.recommendations ? `<div class="suggestion-item-message">${check.recommendations.join(', ')}</div>` : ''}
                    </div>
                `;
            });
            
            html += '</div>';
            
            // Display in modal or new section
            alert('Audit completed! Check console for details.');
            console.log(audit);
        }
        
        // Export Data
        function exportData() {
            showNotification('Exporting data...', 'info');
            // Implementation for export
        }
        
        // Utility Functions
        function getScoreClass(score) {
            if (score >= 80) return 'excellent';
            if (score >= 60) return 'good';
            return 'warning';
        }
        
        function showNotification(message, type = 'info') {
            const bgColor = {
                'success': '#d4edda',
                'error': '#f8d7da',
                'warning': '#fff3cd',
                'info': '#d1ecf1'
            };
            
            const textColor = {
                'success': '#155724',
                'error': '#721c24',
                'warning': '#856404',
                'info': '#0c5460'
            };
            
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 15px 20px;
                background: ${bgColor[type] || bgColor['info']};
                color: ${textColor[type] || textColor['info']};
                border-radius: 6px;
                z-index: 10000;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                max-width: 400px;
            `;
            notification.textContent = message;
            document.body.appendChild(notification);
            
            setTimeout(() => notification.remove(), 4000);
        }
        
        // Live Snippet Preview
        function updateSnippetPreview() {
            const title = document.getElementById('title')?.value || '';
            const description = document.getElementById('meta_description')?.value || '';
            const slug = document.getElementById('slug')?.value || '';
            
            let url = window.location.hostname;
            if (slug) url += '/' + slug;
            
            // Update preview visually (implementation depends on UI structure)
            console.log('Preview:', { title, description, url });
        }
        
        // Auto-save on input
        document.querySelectorAll('#seoForm input, #seoForm textarea').forEach(field => {
            field.addEventListener('blur', () => {
                saveSEOData();
            });
        });
        
        // Character counters
        document.getElementById('title')?.addEventListener('input', function() {
            document.getElementById('titleCount').textContent = this.value.length;
        });
        
        document.getElementById('meta_description')?.addEventListener('input', function() {
            document.getElementById('descCount').textContent = this.value.length;
        });
        
        // Load Products via AJAX
        function loadProducts() {
            const container = document.getElementById('productsContainer');
            if (!container) return;
            
            container.innerHTML = '<p style="text-align: center; color: #999;">Loading products...</p>';
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=load_products'
            })
            .then(r => {
                console.log('Response status:', r.status);
                return r.text().then(text => {
                    console.log('Response text:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('Failed to parse JSON:', e);
                        throw new Error('Invalid JSON response: ' + text);
                    }
                });
            })
            .then(data => {
                console.log('Parsed data:', data);
                if (data.success && data.products) {
                    let html = `<table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="border-bottom: 2px solid #ddd;">
                                <th style="padding: 10px; text-align: left;">Product Name</th>
                                <th style="padding: 10px; text-align: left;">SEO Title</th>
                                <th style="padding: 10px; text-align: center;">Score</th>
                                <th style="padding: 10px; text-align: center;">Action</th>
                            </tr>
                        </thead>
                        <tbody>`;
                    
                    data.products.forEach(product => {
                        html += `<tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 10px;">${product.title}</td>
                            <td style="padding: 10px;">${product.seo_title || 'Not set'}</td>
                            <td style="padding: 10px; text-align: center; font-weight: bold; color: #d16baf;">${product.seo_score}</td>
                            <td style="padding: 10px; text-align: center;">
                                <button onclick="editProductSEO(${product.id})" style="padding: 5px 10px; background: #d16baf; color: white; border: none; border-radius: 4px; cursor: pointer;">Edit</button>
                            </td>
                        </tr>`;
                    });
                    
                    html += `</tbody></table>`;
                    container.innerHTML = html;
                    showNotification('Loaded ' + data.count + ' products', 'success');
                } else {
                    const errorMsg = data.message || data.error || 'Unknown error';
                    container.innerHTML = '<p style="color: #c00;">Error loading products: ' + errorMsg + '</p>';
                    showNotification('Error: ' + errorMsg, 'error');
                    console.error('Error response:', data);
                }
            })
            .catch(err => {
                console.error('Fetch error:', err);
                container.innerHTML = '<p style="color: #c00;">Error loading products: ' + err.message + '</p>';
                showNotification('Error loading products: ' + err.message, 'error');
            });
        }
        
        // Load Blogs via AJAX
        function loadBlogs() {
            const container = document.getElementById('blogsContainer');
            if (!container) return;
            
            container.innerHTML = '<p style="text-align: center; color: #999;">Loading blogs...</p>';
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=load_blogs'
            })
            .then(r => {
                console.log('Response status:', r.status);
                return r.text().then(text => {
                    console.log('Response text:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('Failed to parse JSON:', e);
                        throw new Error('Invalid JSON response: ' + text);
                    }
                });
            })
            .then(data => {
                console.log('Parsed blog data:', data);
                if (data.success && data.blogs) {
                    let html = `<table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="border-bottom: 2px solid #ddd;">
                                <th style="padding: 10px; text-align: left;">Blog Title</th>
                                <th style="padding: 10px; text-align: left;">SEO Title</th>
                                <th style="padding: 10px; text-align: center;">Score</th>
                                <th style="padding: 10px; text-align: center;">Action</th>
                            </tr>
                        </thead>
                        <tbody>`;
                    
                    data.blogs.forEach(blog => {
                        html += `<tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 10px;">${blog.title}</td>
                            <td style="padding: 10px;">${blog.seo_title || 'Not set'}</td>
                            <td style="padding: 10px; text-align: center; font-weight: bold; color: #d16baf;">${blog.seo_score}</td>
                            <td style="padding: 10px; text-align: center;">
                                <button onclick="editBlogSEO(${blog.id})" style="padding: 5px 10px; background: #d16baf; color: white; border: none; border-radius: 4px; cursor: pointer;">Edit</button>
                            </td>
                        </tr>`;
                    });
                    
                    html += `</tbody></table>`;
                    container.innerHTML = html;
                    showNotification('Loaded ' + data.count + ' blogs', 'success');
                } else {
                    const errorMsg = data.message || data.error || 'Unknown error';
                    container.innerHTML = '<p style="color: #c00;">Error loading blogs: ' + errorMsg + '</p>';
                    showNotification('Error: ' + errorMsg, 'error');
                    console.error('Error response:', data);
                }
            })
            .catch(err => {
                console.error('Fetch error:', err);
                container.innerHTML = '<p style="color: #c00;">Error loading blogs: ' + err.message + '</p>';
                showNotification('Error loading blogs: ' + err.message, 'error');
            });
        }
        
        // Load Categories via AJAX
        function loadCategories() {
            const container = document.getElementById('categoriesContainer');
            if (!container) return;
            
            container.innerHTML = '<p style="text-align: center; color: #999;">Loading categories...</p>';
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=load_categories'
            })
            .then(r => {
                console.log('Response status:', r.status);
                return r.text().then(text => {
                    console.log('Response text:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('Failed to parse JSON:', e);
                        throw new Error('Invalid JSON response: ' + text);
                    }
                });
            })
            .then(data => {
                console.log('Parsed category data:', data);
                if (data.success && data.categories) {
                    let html = `<table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="border-bottom: 2px solid #ddd;">
                                <th style="padding: 10px; text-align: left;">Category Name</th>
                                <th style="padding: 10px; text-align: left;">SEO Title</th>
                                <th style="padding: 10px; text-align: center;">Score</th>
                                <th style="padding: 10px; text-align: center;">Action</th>
                            </tr>
                        </thead>
                        <tbody>`;
                    
                    data.categories.forEach(category => {
                        html += `<tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 10px;">${category.name}</td>
                            <td style="padding: 10px;">${category.seo_title || 'Not set'}</td>
                            <td style="padding: 10px; text-align: center; font-weight: bold; color: #d16baf;">${category.seo_score}</td>
                            <td style="padding: 10px; text-align: center;">
                                <button onclick="editCategorySEO(${category.id})" style="padding: 5px 10px; background: #d16baf; color: white; border: none; border-radius: 4px; cursor: pointer;">Edit</button>
                            </td>
                        </tr>`;
                    });
                    
                    html += `</tbody></table>`;
                    container.innerHTML = html;
                    showNotification('Loaded ' + data.count + ' categories', 'success');
                } else {
                    const errorMsg = data.message || data.error || 'Unknown error';
                    container.innerHTML = '<p style="color: #c00;">Error loading categories: ' + errorMsg + '</p>';
                    showNotification('Error: ' + errorMsg, 'error');
                    console.error('Error response:', data);
                }
            })
            .catch(err => {
                console.error('Fetch error:', err);
                container.innerHTML = '<p style="color: #c00;">Error loading categories: ' + err.message + '</p>';
                showNotification('Error loading categories: ' + err.message, 'error');
            });
        }
        
        // Create modal dialog HTML
        function createEditModal(itemId, itemType) {
            const modal = document.createElement('div');
            modal.id = 'editModal';
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.7);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                overflow-y: auto;
            `;
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    padding: 30px;
                    border-radius: 8px;
                    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                    max-width: 700px;
                    width: 95%;
                    // margin: 20px;
                        margin-top: 700px;
                ">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3 style="margin: 0; color: #d16baf;">✏️ Edit SEO Data</h3>
                        <span style="font-size: 12px; color: #999; background: #f5f5f5; padding: 5px 10px; border-radius: 4px;">
                            SEO Score: <span id="liveScore" style="font-weight: bold; color: #d16baf;">-</span>/100
                        </span>
                    </div>
                    
                    <div id="yoast-seo-container" style="margin-bottom: 20px;"></div>
                    
                    <div style="border-bottom: 2px solid #eee; padding-bottom: 15px; margin-bottom: 15px;">
                        <strong>Live Suggestions:</strong>
                        <div id="liveSuggestions" style="margin-top: 10px;">
                            <small style="color: #999;">Fill in fields to see suggestions...</small>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-weight: bold; margin-bottom: 5px;">🎯 SEO Title (50-60 chars)</label>
                        <input type="text" id="modal_seo_title" placeholder="Enter compelling SEO title" style="
                            width: 100%;
                            padding: 10px;
                            border: 2px solid #ddd;
                            border-radius: 4px;
                            box-sizing: border-box;
                            font-size: 14px;
                        " maxlength="255" oninput="updateLivePreview()">
                        <div style="display: flex; justify-content: space-between; margin-top: 5px;">
                            <small style="color: #666;"><span id="title_count">0</span>/60 characters</small>
                            <small id="title_status" style="color: #999;"></small>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-weight: bold; margin-bottom: 5px;">📝 Meta Description (120-160 chars)</label>
                        <textarea id="modal_seo_description" placeholder="Enter compelling meta description" style="
                            width: 100%;
                            padding: 10px;
                            border: 2px solid #ddd;
                            border-radius: 4px;
                            box-sizing: border-box;
                            font-size: 14px;
                            min-height: 80px;
                            font-family: Arial, sans-serif;
                        " maxlength="255" oninput="updateLivePreview()"></textarea>
                        <div style="display: flex; justify-content: space-between; margin-top: 5px;">
                            <small style="color: #666;"><span id="desc_count">0</span>/160 characters</small>
                            <small id="desc_status" style="color: #999;"></small>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-weight: bold; margin-bottom: 5px;">🔑 Focus Keyword</label>
                        <input type="text" id="modal_seo_keyword" placeholder="Enter main target keyword" style="
                            width: 100%;
                            padding: 10px;
                            border: 2px solid #ddd;
                            border-radius: 4px;
                            box-sizing: border-box;
                            font-size: 14px;
                        " oninput="updateLivePreview()">
                        <small id="keyword_status" style="display: block; margin-top: 5px; color: #999;"></small>
                    </div>
                    
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-weight: bold; margin-bottom: 5px;">🔗 URL Slug (Auto-generated)</label>
                        <div style="display: flex; gap: 10px;">
                            <input type="text" id="modal_slug" placeholder="Will auto-generate from title" style="
                                flex: 1;
                                padding: 10px;
                                border: 2px solid #ddd;
                                border-radius: 4px;
                                font-size: 14px;
                            " oninput="updateLivePreview()">
                            <button onclick="generateSlugFromTitle()" style="
                                padding: 10px 15px;
                                background: #d16baf;
                                color: white;
                                border: none;
                                border-radius: 4px;
                                cursor: pointer;
                                font-weight: bold;
                                white-space: nowrap;
                            ">Generate</button>
                        </div>
                        <small id="slug_status" style="display: block; margin-top: 5px; color: #999;"></small>
                    </div>
                    
                    <div style="margin-bottom: 15px; border-top: 2px solid #eee; padding-top: 15px;">
                        <label style="display: block; font-weight: bold; margin-bottom: 5px;">📋 Schema Markup</label>
                        <select id="modal_schema_type" style="width: 100%; padding: 10px; border: 2px solid #ddd; border-radius: 4px; margin-bottom: 10px;" onchange="updateSchemaPreview()">
                            <option value="">Select Schema Type</option>
                            <option value="product">Product</option>
                            <option value="article">Article</option>
                            <option value="blog">Blog Post</option>
                            <option value="organization">Organization</option>
                            <option value="breadcrumb">Breadcrumb</option>
                        </select>
                        <button onclick="generateSchemaMarkup()" style="padding: 8px 15px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; margin-bottom: 10px;">Generate Schema</button>
                        <textarea id="modal_schema_markup" placeholder="Schema markup will appear here..." style="width: 100%; padding: 10px; border: 2px solid #ddd; border-radius: 4px; min-height: 100px; font-family: monospace; font-size: 12px;"></textarea>
                        <small style="color: #666; display: block; margin-top: 5px;">Schema markup helps search engines understand your content better</small>
                    </div>
                    
                    <div style="margin-bottom: 15px; border-top: 2px solid #eee; padding-top: 15px;">
                        <label style="display: block; font-weight: bold; margin-bottom: 5px;">🔗 Internal Linking</label>
                        <div style="background: #f9f9f9; padding: 10px; border-radius: 4px; margin-bottom: 10px;">
                            <small style="color: #666;">Add internal links to related content. Format: Link Text|URL (one per line)</small>
                        </div>
                        <textarea id="modal_internal_links" placeholder="Example:&#10;Related Products|/products.php&#10;Blog Post|/blog.php?id=1" style="width: 100%; padding: 10px; border: 2px solid #ddd; border-radius: 4px; min-height: 80px; font-family: Arial, sans-serif; font-size: 13px;"></textarea>
                        <button onclick="suggestInternalLinks()" style="padding: 8px 15px; background: #17a2b8; color: white; border: none; border-radius: 4px; cursor: pointer; margin-top: 5px;">💡 Suggest Links</button>
                    </div>
                    
                    <div style="background: #f9f9f9; padding: 15px; border-radius: 4px; margin-bottom: 15px;">
                        <strong>📊 Quick Stats:</strong>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; font-size: 12px;">
                            <div>Title Length: <span id="stat_title_len" style="font-weight: bold;">0</span></div>
                            <div>Desc Length: <span id="stat_desc_len" style="font-weight: bold;">0</span></div>
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 10px; justify-content: flex-end;">
                        <button onclick="closeEditModal()" style="
                            padding: 10px 20px;
                            background: #f0f0f0;
                            color: #333;
                            border: none;
                            border-radius: 4px;
                            cursor: pointer;
                            font-weight: bold;
                            transition: all 0.3s;
                        " onmouseover="this.style.background='#e0e0e0'" onmouseout="this.style.background='#f0f0f0'">Cancel</button>
                        <button onclick="saveEditModal('${itemType}', ${itemId})" style="
                            padding: 10px 20px;
                            background: #d16baf;
                            color: white;
                            border: none;
                            border-radius: 4px;
                            cursor: pointer;
                            font-weight: bold;
                            transition: all 0.3s;
                        " onmouseover="this.style.background='#c0478e'" onmouseout="this.style.background='#d16baf'">✅ Save SEO</button>
                    </div>
                </div>
            `;
            
            // Initialize Yoast SEO UI after modal is added to DOM
            setTimeout(() => {
                if (window.yoastSEO) {
                    window.yoastSEO.container = document.getElementById('yoast-seo-container');
                    window.yoastSEO.init();
                } else {
                    window.yoastSEO = new YoastSEOUI('yoast-seo-container');
                    window.yoastSEO.init();
                }
            }, 100);
            
            return modal;
        }
        
        // Generate slug from title
        function generateSlugFromTitle() {
            const title = document.getElementById('modal_seo_title').value.trim();
            if (!title) {
                showNotification('Enter a title first', 'warning');
                return;
            }
            
            // Generate slug: lowercase, replace spaces with hyphens, remove special chars
            let slug = title.toLowerCase();
            slug = slug.replace(/\s+/g, '-');
            slug = slug.replace(/[^a-z0-9\-]/g, '');
            slug = slug.replace(/-+/g, '-');
            slug = slug.replace(/^-+|-+$/g, '');
            
            document.getElementById('modal_slug').value = slug;
            updateLivePreview();
            showNotification('Slug auto-generated!', 'success');
        }
        
        // Update live preview and validation
        function updateLivePreview() {
            const title = document.getElementById('modal_seo_title').value;
            const description = document.getElementById('modal_seo_description').value;
            const keyword = document.getElementById('modal_seo_keyword').value;
            const slug = document.getElementById('modal_slug').value;
            
            // Update character counts
            document.getElementById('title_count').textContent = title.length;
            document.getElementById('desc_count').textContent = description.length;
            document.getElementById('stat_title_len').textContent = title.length;
            document.getElementById('stat_desc_len').textContent = description.length;
            
            // Update status indicators
            if (title.length < 30) {
                document.getElementById('title_status').textContent = '⚠️ Too short';
                document.getElementById('title_status').style.color = '#ff9800';
            } else if (title.length > 60) {
                document.getElementById('title_status').textContent = '⚠️ Too long';
                document.getElementById('title_status').style.color = '#ff9800';
            } else {
                document.getElementById('title_status').textContent = '✅ Perfect length';
                document.getElementById('title_status').style.color = '#4caf50';
            }
            
            if (description.length < 120) {
                document.getElementById('desc_status').textContent = '⚠️ Too short';
                document.getElementById('desc_status').style.color = '#ff9800';
            } else if (description.length > 160) {
                document.getElementById('desc_status').textContent = '⚠️ Too long';
                document.getElementById('desc_status').style.color = '#ff9800';
            } else {
                document.getElementById('desc_status').textContent = '✅ Perfect length';
                document.getElementById('desc_status').style.color = '#4caf50';
            }
            
            if (slug) {
                if (/[^a-z0-9\-]/.test(slug)) {
                    document.getElementById('slug_status').textContent = '❌ Invalid characters';
                    document.getElementById('slug_status').style.color = '#f44336';
                } else {
                    document.getElementById('slug_status').textContent = '✅ Valid slug';
                    document.getElementById('slug_status').style.color = '#4caf50';
                }
            }
            
            // Calculate live SEO score
            let score = 0;
            if (title.length >= 30 && title.length <= 60) score += 25;
            else if (title.length > 0) score += 15;
            
            if (description.length >= 120 && description.length <= 160) score += 25;
            else if (description.length > 0) score += 15;
            
            if (keyword && keyword.length > 0) score += 20;
            if (slug && slug.length > 0) score += 10;
            if (/[^a-z0-9\-]/.test(slug) === false && slug) score += 10;
            
            document.getElementById('liveScore').textContent = Math.min(score, 100);
            document.getElementById('liveScore').style.color = score >= 80 ? '#4caf50' : score >= 60 ? '#ff9800' : '#f44336';
            
            // Update suggestions
            updateLiveSuggestions(title, description, keyword, slug);
        }
        
        function updateLiveSuggestions(title, description, keyword, slug) {
            let suggestions = [];
            
            if (!title) suggestions.push({ type: 'error', text: '⚠️ Add SEO Title' });
            else if (title.length < 30) suggestions.push({ type: 'warning', text: '⚠️ Title too short (min 30)' });
            else if (title.length > 60) suggestions.push({ type: 'warning', text: '⚠️ Title too long (max 60)' });
            else suggestions.push({ type: 'success', text: '✅ Title length perfect' });
            
            if (!description) suggestions.push({ type: 'error', text: '⚠️ Add Meta Description' });
            else if (description.length < 120) suggestions.push({ type: 'warning', text: '⚠️ Description too short (min 120)' });
            else if (description.length > 160) suggestions.push({ type: 'warning', text: '⚠️ Description too long (max 160)' });
            else suggestions.push({ type: 'success', text: '✅ Description length perfect' });
            
            if (keyword) suggestions.push({ type: 'success', text: '✅ Focus keyword added' });
            else suggestions.push({ type: 'warning', text: '⚠️ Add focus keyword' });
            
            if (slug) {
                if (/[^a-z0-9\-]/.test(slug)) suggestions.push({ type: 'error', text: '❌ Slug has invalid characters' });
                else suggestions.push({ type: 'success', text: '✅ Slug is valid' });
            }
            
            const suggestionsDiv = document.getElementById('liveSuggestions');
            suggestionsDiv.innerHTML = suggestions.map(s => `
                <div style="padding: 5px; margin: 3px 0; border-radius: 3px; font-size: 12px; background: ${s.type === 'error' ? '#ffebee' : s.type === 'warning' ? '#fff3e0' : '#e8f5e9'}; color: ${s.type === 'error' ? '#c62828' : s.type === 'warning' ? '#e65100' : '#2e7d32'};">
                    ${s.text}
                </div>
            `).join('');
        }
        
        function closeEditModal() {
            const modal = document.getElementById('editModal');
            if (modal) modal.remove();
        }
        
        function generateSchemaMarkup() {
            const schemaType = document.getElementById('modal_schema_type').value;
            if (!schemaType) {
                showNotification('Please select a schema type', 'warning');
                return;
            }
            
            const title = document.getElementById('modal_seo_title').value;
            const description = document.getElementById('modal_seo_description').value;
            const keyword = document.getElementById('modal_seo_keyword').value;
            
            fetch('admin_seo_manager.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=generate_schema&schema_type=${schemaType}&title=${encodeURIComponent(title)}&description=${encodeURIComponent(description)}&focus_keyword=${encodeURIComponent(keyword)}`
            })
            .then(r => r.json())
            .then(data => {
                if (data.success && data.schema) {
                    document.getElementById('modal_schema_markup').value = data.schema;
                    showNotification('Schema markup generated!', 'success');
                } else {
                    showNotification('Error generating schema: ' + (data.message || 'Unknown error'), 'error');
                }
            })
            .catch(err => {
                showNotification('Error: ' + err.message, 'error');
            });
        }
        
        function updateSchemaPreview() {
            // Preview update when schema type changes
        }
        
        function suggestInternalLinks() {
            const keyword = document.getElementById('modal_seo_keyword').value;
            const itemType = document.querySelector('[name="item_type"]')?.value || 'product';
            
            if (!keyword) {
                showNotification('Enter a focus keyword first to get link suggestions', 'warning');
                return;
            }
            
            fetch('admin_seo_manager.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=suggest_internal_links&keyword=${encodeURIComponent(keyword)}&item_type=${itemType}`
            })
            .then(r => r.json())
            .then(data => {
                if (data.success && data.links && data.links.length > 0) {
                    const linksText = data.links.map(link => `${link.text}|${link.url}`).join('\\n');
                    document.getElementById('modal_internal_links').value = linksText;
                    showNotification(`Found ${data.links.length} related links!`, 'success');
                } else {
                    showNotification('No related links found. Add links manually.', 'info');
                }
            })
            .catch(err => {
                showNotification('Error: ' + err.message, 'error');
            });
        }
        
        function saveEditModal(itemType, itemId) {
            const title = document.getElementById('modal_seo_title').value.trim();
            const description = document.getElementById('modal_seo_description').value.trim();
            const keyword = document.getElementById('modal_seo_keyword').value.trim();
            const slug = document.getElementById('modal_slug').value.trim();
            const schemaMarkup = document.getElementById('modal_schema_markup').value.trim();
            const internalLinks = document.getElementById('modal_internal_links').value.trim();
            
            // Validation
            if (!title || title.length < 30) {
                showNotification('Title must be at least 30 characters', 'error');
                return;
            }
            if (!description || description.length < 120) {
                showNotification('Description must be at least 120 characters', 'error');
                return;
            }
            if (!keyword) {
                showNotification('Please add a focus keyword', 'error');
                return;
            }
            if (!slug) {
                showNotification('Please generate or add a URL slug', 'error');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', itemType === 'product' ? 'save_product_seo' : 'save_blog_seo');
            formData.append(itemType === 'product' ? 'product_id' : 'blog_id', itemId);
            formData.append('title', title);
            formData.append('meta_description', description);
            formData.append('focus_keyword', keyword);
            formData.append('slug', slug);
            formData.append('schema_markup', schemaMarkup);
            formData.append('internal_links', internalLinks);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showNotification((itemType === 'product' ? 'Product' : 'Blog') + ' SEO saved!', 'success');
                    closeEditModal();
                    itemType === 'product' ? loadProducts() : loadBlogs();
                } else {
                    showNotification(data.message || 'Error saving', 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showNotification('Error saving SEO data', 'error');
            });
        }
        
        // Edit Product SEO (creates modal)
        function editProductSEO(productId) {
            const modal = createEditModal(productId, 'product');
            document.body.appendChild(modal);
            
            // Add character counter listeners
            document.getElementById('modal_seo_title').addEventListener('input', (e) => {
                document.getElementById('title_count').textContent = e.target.value.length;
            });
            document.getElementById('modal_seo_description').addEventListener('input', (e) => {
                document.getElementById('desc_count').textContent = e.target.value.length;
            });
        }
        
        // Edit Blog SEO (creates modal)
        function editBlogSEO(blogId) {
            const modal = createEditModal(blogId, 'blog');
            document.body.appendChild(modal);
            
            // Add character counter listeners
            document.getElementById('modal_seo_title').addEventListener('input', (e) => {
                document.getElementById('title_count').textContent = e.target.value.length;
            });
            document.getElementById('modal_seo_description').addEventListener('input', (e) => {
                document.getElementById('desc_count').textContent = e.target.value.length;
            });
        }
        
        // Edit Category SEO (creates modal)
        function editCategorySEO(categoryId) {
            const modal = createEditModal(categoryId, 'category');
            document.body.appendChild(modal);
            
            // Add character counter listeners
            document.getElementById('modal_seo_title').addEventListener('input', (e) => {
                document.getElementById('title_count').textContent = e.target.value.length;
            });
            document.getElementById('modal_seo_description').addEventListener('input', (e) => {
                document.getElementById('desc_count').textContent = e.target.value.length;
            });
        }
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', () => {
            // Set initial character counts
            const titleInput = document.getElementById('title');
            const descInput = document.getElementById('meta_description');
            
            if (titleInput) document.getElementById('titleCount').textContent = titleInput.value.length;
            if (descInput) document.getElementById('descCount').textContent = descInput.value.length;
            
            // Auto-load products, categories, and blogs based on current page
            const currentAction = window.location.search.includes('seo-products') ? 'products' :
                                   window.location.search.includes('seo-categories') ? 'categories' :
                                   window.location.search.includes('seo-blogs') ? 'blogs' : null;
            
            if (currentAction === 'products' && document.getElementById('productsContainer')) {
                setTimeout(() => loadProducts(), 500);
            } else if (currentAction === 'categories' && document.getElementById('categoriesContainer')) {
                setTimeout(() => loadCategories(), 500);
            } else if (currentAction === 'blogs' && document.getElementById('blogsContainer')) {
                setTimeout(() => loadBlogs(), 500);
            }
        });
        
        // Also auto-load when page becomes visible (if user switches tabs)
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) return;
            
            const currentAction = window.location.search.includes('seo-products') ? 'products' :
                                   window.location.search.includes('seo-categories') ? 'categories' :
                                   window.location.search.includes('seo-blogs') ? 'blogs' : null;
            
            if (currentAction === 'products' && document.getElementById('productsContainer')) {
                loadProducts();
            } else if (currentAction === 'categories' && document.getElementById('categoriesContainer')) {
                loadCategories();
            } else if (currentAction === 'blogs' && document.getElementById('blogsContainer')) {
                loadBlogs();
            }
        });
        
        // Bulk Apply SEO
        function bulkApplySEO(itemType) {
            if (!confirm(`This will automatically apply SEO to ALL ${itemType}s. Continue?`)) {
                return;
            }
            
            showNotification('Applying SEO to all ' + itemType + 's...', 'info');
            
            fetch('admin_seo_manager.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=bulk_apply_seo&item_type=${itemType}&auto_generate=true`
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showNotification(`✅ Successfully applied SEO to ${data.processed} ${itemType}s!`, 'success');
                    if (itemType === 'product') {
                        loadProducts();
                    } else {
                        loadBlogs();
                    }
                } else {
                    showNotification('Error: ' + (data.message || 'Unknown error'), 'error');
                }
            })
            .catch(err => {
                showNotification('Error: ' + err.message, 'error');
            });
        }
    </script>
</body>
</html>

<?php

function get_page_title($action) {
    $titles = [
        'dashboard' => ' SEO Dashboard',
        'pages' => ' Pages & Posts',
        'meta-tags' => ' Meta Tags',
        'readability' => ' Readability Analysis',
        'keywords' => ' Keyword Optimization',
        'schema' => ' Schema Markup',
        'analytics' => ' Analytics',
        'social-tags' => ' Social Media Tags',
        'seo-products' => ' Products SEO',
        'seo-blogs' => ' Blogs SEO',
        'seo-categories' => ' Categories SEO',
        'seo-homepage' => ' Homepage SEO',
        'seo-about' => ' About Page SEO',
        'seo-contact' => ' Contact Page SEO',
        'settings' => ' Settings'
    ];
    
    return $titles[$action] ?? 'SEO Manager';
}

function render_dashboard() {
    global $analytics, $seo_plugin;
    
    $report = $analytics->generateReport(30);
    
    // Extract values to avoid ?? operator in heredoc
    $health_score = $report['health_score'] ?? 0;
    $total_impressions = $report['overview']['total_impressions'] ?? 0;
    $total_clicks = $report['overview']['total_clicks'] ?? 0;
    $avg_position = $report['overview']['avg_position'] ?? 0;
    $avg_ctr = $report['overview']['avg_ctr'] ?? 0;
    
    echo <<<HTML
    <!-- SEO Health Check Widget -->
    <div id="seo-health-widget"></div>
    
    <div class="grid-2">
        <div class="card">
            <div class="card-title">SEO Health</div>
            <div class="seo-score">
                <div class="seo-score-circle excellent" style="width: 60px; height: 60px; font-size: 20px;">
                    {$health_score}
                </div>
                <div class="seo-score-info">
                    <h3>Overall Score</h3>
                    <p>Last 30 days</p>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-title">Quick Actions</div>
            <a href="?action=meta-tags" class="btn btn-primary" style="width: 100%; justify-content: center; margin-bottom: 10px;">Edit Meta Tags</a>
            <a href="?action=readability" class="btn btn-primary" style="width: 100%; justify-content: center; margin-bottom: 10px;">Check Readability</a>
            <a href="?action=keywords" class="btn btn-primary" style="width: 100%; justify-content: center;">Optimize Keywords</a>
        </div>
    </div>
    
    <div class="analytics-grid full-width">
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">{$total_impressions}</div>
            <div class="analytics-card-label">Total Impressions</div>
        </div>
        
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">{$total_clicks}</div>
            <div class="analytics-card-label">Total Clicks</div>
        </div>
        
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">{$avg_position}</div>
            <div class="analytics-card-label">Avg Position</div>
        </div>
        
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">{$avg_ctr}%</div>
            <div class="analytics-card-label">Click Through Rate</div>
        </div>
    </div>
HTML;
}

function render_pages() {
    global $seo_plugin;
    
    $pages = $seo_plugin->getAllSEOData(null, 20, 0);
    
    echo <<<HTML
    <div class="card">
        <div class="card-title">Pages & Posts SEO</div>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Page/Post</th>
                        <th>Type</th>
                        <th>SEO Score</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
HTML;
    
    if ($pages && $pages->num_rows > 0) {
        while ($page = $pages->fetch_assoc()) {
            $score = $seo_plugin->calculateSEOScore($page);
            $status = $seo_plugin->getSEOScoreStatus($score);
            
            echo <<<HTML
                    <tr>
                        <td>{$page['title']}</td>
                        <td><span class="badge badge-success">{$page['page_type']}</span></td>
                        <td><strong>$score/100</strong></td>
                        <td><span class="badge badge-success">{$status['status']}</span></td>
                        <td>
                            <a href="?action=meta-tags&page_type={$page['page_type']}&page_id={$page['page_id']}" class="btn btn-primary" style="font-size: 12px;">Edit</a>
                        </td>
                    </tr>
HTML;
        }
    } else {
        echo '<tr><td colspan="5" style="text-align: center; padding: 30px;">No pages found</td></tr>';
    }
    
    echo '</tbody></table></div></div>';
}

function render_meta_tags() {
    global $seo_plugin;
    
    $page_type = $_GET['page_type'] ?? 'page';
    $page_id = $_GET['page_id'] ?? 1;
    
    $seo_data = $seo_plugin->getSEOData($page_type, $page_id) ?? [];
    
    // Extract values to avoid ?? operator in heredoc
    $title = $seo_data['title'] ?? '';
    $meta_description = $seo_data['meta_description'] ?? '';
    $focus_keyword = $seo_data['focus_keyword'] ?? '';
    $slug = $seo_data['slug'] ?? '';
    $og_title = $seo_data['og_title'] ?? '';
    $og_description = $seo_data['og_description'] ?? '';
    $og_image = $seo_data['og_image'] ?? '';
    $twitter_title = $seo_data['twitter_title'] ?? '';
    $twitter_description = $seo_data['twitter_description'] ?? '';
    $twitter_image = $seo_data['twitter_image'] ?? '';
    
    echo <<<HTML
    <!-- Google Snippet Preview -->
    <div id="google-snippet-preview"></div>
    
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Meta Tag Editor</div>
            <form id="seoForm" onsubmit="saveSEOData(); return false;">
                <input type="hidden" name="page_type" value="$page_type">
                <input type="hidden" name="page_id" value="$page_id">
                
                <div class="form-group">
                    <label>Page Title</label>
                    <input type="text" id="title" name="title" value="$title" placeholder="Page title (30-60 chars)">
                    <div class="char-count"><span id="titleCount">0</span>/60</div>
                </div>
                
                <div class="form-group">
                    <label>Meta Description</label>
                    <textarea id="meta_description" name="meta_description" placeholder="Meta description (120-160 chars)">$meta_description</textarea>
                    <div class="char-count"><span id="descCount">0</span>/160</div>
                </div>
                
                <div class="form-group">
                    <label>Focus Keyword</label>
                    <input type="text" name="focus_keyword" value="$focus_keyword" placeholder="Main keyword to target">
                </div>
                
                <div class="form-group">
                    <label>URL Slug</label>
                    <input type="text" id="slug" name="slug" value="$slug" placeholder="url-slug">
                </div>
                
                <button type="submit" class="btn btn-success" style="width: 100%;">Save SEO Data</button>
            </form>
        </div>
        
        <div class="card">
            <div class="card-title">Open Graph & Twitter</div>
            <form id="socialTagsForm" onsubmit="saveSocialTags(); return false;">
                <input type="hidden" name="page_type" value="$page_type">
                <input type="hidden" name="page_id" value="$page_id">
                
                <div class="form-group">
                    <label>OG Title</label>
                    <input type="text" id="og_title" name="og_title" value="$og_title" placeholder="OpenGraph title">
                </div>
                
                <div class="form-group">
                    <label>OG Description</label>
                    <textarea id="og_description" name="og_description" placeholder="OpenGraph description">$og_description</textarea>
                </div>
                
                <div class="form-group">
                    <label>OG Image URL</label>
                    <input type="url" id="og_image" name="og_image" value="$og_image" placeholder="https://example.com/image.jpg">
                </div>
                
                <div class="form-group">
                    <label>Twitter Title</label>
                    <input type="text" id="twitter_title" name="twitter_title" value="$twitter_title" placeholder="Twitter title">
                </div>
                
                <div class="form-group">
                    <label>Twitter Description</label>
                    <textarea id="twitter_description" name="twitter_description" placeholder="Twitter description">$twitter_description</textarea>
                </div>
                
                <div class="form-group">
                    <label>Twitter Image URL</label>
                    <input type="url" id="twitter_image" name="twitter_image" value="$twitter_image" placeholder="https://example.com/image.jpg">
                </div>
                
                <button type="submit" class="btn btn-success" style="width: 100%;">💾 Save Social Tags</button>
            </form>
        </div>
    </div>
HTML;
}

function render_readability() {
    echo <<<HTML
    <div class="card">
        <div class="card-title">Content Readability Analyzer</div>
        
        <div class="form-group">
            <label>Paste Your Content Here</label>
            <textarea id="content" placeholder="Paste your article or page content to analyze..."></textarea>
        </div>
        
        <button type="button" class="btn btn-success" onclick="analyzeReadability()" style="width: 100%;"> Analyze Readability</button>
        
        <div class="loading">
            <div class="spinner"></div>
            <p>Analyzing content...</p>
        </div>
        
        <div id="readabilityResults" style="margin-top: 30px;"></div>
    </div>
HTML;
}

function render_keywords() {
    echo <<<HTML
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Keyword Analyzer</div>
            
            <div class="form-group">
                <label>Focus Keyword</label>
                <input type="text" id="focusKeyword" placeholder="Your target keyword">
            </div>
            
            <div class="form-group">
                <label>Content</label>
                <textarea id="keywordContent" placeholder="Paste content to analyze..."></textarea>
            </div>
            
            <button type="button" class="btn btn-success" onclick="analyzeKeywords()" style="width: 100%; margin-bottom: 10px;"> Analyze Keywords</button>
        </div>
        
        <div class="card">
            <div class="card-title">Keyword Suggestions</div>
            <div id="keywordResults"></div>
        </div>
    </div>
HTML;
}

function render_schema() {
    echo <<<HTML
    <div class="card">
        <div class="card-title">Schema Markup Generator</div>
        
        <div class="form-group">
            <label>Schema Type</label>
            <select id="schemaType">
                <option value="article">Article</option>
                <option value="product">Product</option>
                <option value="organization">Organization</option>
                <option value="blog">Blog Post</option>
                <option value="faq">FAQ</option>
                <option value="breadcrumb">Breadcrumb</option>
                <option value="localbusiness">Local Business</option>
            </select>
        </div>
        
        <div class="form-group">
            <label>Schema Title</label>
            <input type="text" id="schemaTitle" placeholder="Title">
        </div>
        
        <div class="form-group">
            <label>Description</label>
            <textarea id="schemaDescription" placeholder="Description..."></textarea>
        </div>
        
        <button type="button" class="btn btn-success" onclick="generateSchema()" style="width: 100%; margin-bottom: 10px;">Generate Schema</button>
        
        <div id="schemaOutput" style="margin-top: 20px;"></div>
    </div>
HTML;
}

function render_analytics() {
    global $analytics;
    
    $report = $analytics->generateReport(30);
    
    // Extract values to avoid ?? operator in heredoc
    $total_impressions = $report['overview']['total_impressions'] ?? 0;
    $total_clicks = $report['overview']['total_clicks'] ?? 0;
    $avg_ctr = $report['overview']['avg_ctr'] ?? 0;
    $avg_position = $report['overview']['avg_position'] ?? 0;
    
    echo <<<HTML
    <div class="analytics-grid full-width">
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">$total_impressions</div>
            <div class="analytics-card-label">Impressions</div>
        </div>
        
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">$total_clicks</div>
            <div class="analytics-card-label">Clicks</div>
        </div>
        
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">${avg_ctr}%</div>
            <div class="analytics-card-label">CTR</div>
        </div>
        
        <div class="analytics-card">
            <div class="analytics-card-icon"></div>
            <div class="analytics-card-value">$avg_position</div>
            <div class="analytics-card-label">Avg Position</div>
        </div>
    </div>
    
    <div class="card">
        <div class="card-title">Performance Trends</div>
        <p>Analytics visualization would go here - integrate with Chart.js for better visualization</p>
    </div>
HTML;
}

function render_settings() {
    echo <<<HTML
    <div class="card">
        <div class="card-title">SEO Settings</div>
        
        <div class="form-group">
            <label>Analytics Auto-Update</label>
            <select>
                <option>Disabled</option>
                <option>Daily</option>
                <option>Weekly</option>
                <option>Monthly</option>
            </select>
        </div>
        
        <div class="form-group">
            <label>Minimum Readability Score</label>
            <input type="number" min="0" max="100" value="60">
        </div>
        
        <div class="form-group">
            <label>Target SEO Score</label>
            <input type="number" min="0" max="100" value="75">
        </div>
        
        <button type="button" class="btn btn-success" style="width: 100%;"> Save Settings</button>
    </div>
HTML; 
}

function render_social_tags() {
    echo <<<HTML
    <div class="card">
        <div class="card-title">Social Media Tags Manager</div>
        <p style="color: #666; margin-bottom: 20px;">Manage Open Graph and Twitter card tags for all pages and posts</p>
        
        <div class="form-group">
            <label>Select Page/Post</label>
            <select id="socialPageSelect" onchange="loadSocialTagsForPage()">
                <option value="">-- Select a page --</option>
                <option value="homepage">Homepage</option>
                <option value="about">About Page</option>
                <option value="contact">Contact Page</option>
                <option value="blog">Blog</option>
                <option value="products">Products</option>
            </select>
        </div>
    </div>
    
    <div id="socialTagsContainer"></div>
HTML;
}

function render_seo_products() {
    // Get products count from JSON file
    $json_file = __DIR__ . '/data/products.json';
    $total = 0;
    
    if (file_exists($json_file)) {
        $json_content = file_get_contents($json_file);
        $products_data = json_decode($json_content, true);
        $total = is_array($products_data) ? count($products_data) : 0;
    }
    
    echo <<<HTML
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Products SEO Overview</div>
            <p style="color: #666; margin-bottom: 15px;">Optimize your product listings for search engines</p>
            
            <div class="form-group">
                <label>Total Products</label>
                <div style="font-size: 24px; font-weight: bold; color: #d16baf;" id="totalProducts">$total</div>
            </div>
            
            <!-- <div class="form-group">
                <label>SEO Score Distribution</label>
                <p style="font-size: 12px; color: #999;" id="seoDistribution">Loading...</p>
            </div> -->
            
            <button type="button" class="btn btn-success" style="width: 100%; margin-bottom: 10px;" onclick="loadProducts()">📦 Load Products</button>
            <!-- <button type="button" class="btn btn-primary" style="width: 100%; background: #007bff;" onclick="bulkApplySEO('product')">🚀 Auto-Apply SEO to All Products</button> -->
        </div>
        
        <div class="card">
            <div class="card-title">Quick Tips for Products</div>
            <ul style="list-style: disc; margin-left: 20px; line-height: 1.8;">
                <li>Use descriptive product titles (50-60 chars)</li>
                <li>Include keywords in product descriptions</li>
                <li>Add high-quality product images</li>
                <li>Use schema markup for products</li>
                <li>Add customer reviews and ratings</li>
                <li>Optimize meta descriptions (120-160 chars)</li>
            </ul>
        </div>
    </div>
    
    <div class="card" style="margin-top: 20px;">
        <div class="card-title">Products List</div>
        <div id="productsContainer" style="max-height: 600px; overflow-y: auto;">
            <p style="text-align: center; color: #999;">Click "Load Products" to see your products</p>
        </div>
    </div>
HTML;
}

function render_seo_blogs() {
    global $db;
    
    // Get blogs count
    $count_result = $db->query("SELECT COUNT(*) as cnt FROM blogs");
    $count_row = $count_result->fetch_assoc();
    $total = $count_row['cnt'] ?? 0;
    
    echo <<<HTML
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Blog SEO Overview</div>
            <p style="color: #666; margin-bottom: 15px;">Manage SEO for all blog posts and articles</p>
            
            <div class="form-group">
                <label>Total Blog Posts</label>
                <div style="font-size: 24px; font-weight: bold; color: #d16baf;" id="totalBlogs">$total</div>
            </div>
            
            <div class="form-group">
                <label>Posts with SEO Metadata</label>
                <div style="font-size: 20px; font-weight: bold;" id="blogsWithSEO">0</div>
            </div>
            
            <button type="button" class="btn btn-success" style="width: 100%; margin-bottom: 10px;" onclick="loadBlogs()">📝 Load Blog Posts</button>
            <!-- <button type="button" class="btn btn-primary" style="width: 100%; background: #007bff;" onclick="bulkApplySEO('blog')">🚀 Auto-Apply SEO to All Blogs</button> -->
        </div>
        
        <div class="card">
            <div class="card-title">Blog SEO Checklist</div>
            <ul style="list-style: disc; margin-left: 20px; line-height: 1.8;">
                <li>Write unique, compelling titles (50-60 chars)</li>
                <li>Create engaging meta descriptions (120-160 chars)</li>
                <li>Use headers (H1, H2, H3) properly</li>
                <li>Include internal links to related posts</li>
                <li>Optimize images with alt text</li>
                <li>Add schema markup for articles</li>
                <li>Maintain consistent posting schedule</li>
            </ul>
        </div>
    </div>
    
    <div class="card" style="margin-top: 20px;">
        <div class="card-title">Blog Posts List</div>
        <div id="blogsContainer" style="max-height: 600px; overflow-y: auto;">
            <p style="text-align: center; color: #999;">Click "Load Blog Posts" to see your blogs</p>
        </div>
    </div>
HTML;
}

function render_seo_categories() {
    echo <<<HTML
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Categories SEO</div>
            <p style="color: #666; margin-bottom: 15px;">Optimize product and blog categories for search</p>
            
            <div class="form-group">
                <label>Category Type</label>
                <select>
                    <option>Product Categories</option>
                    <option>Blog Categories</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>Total Categories</label>
                <div style="font-size: 24px; font-weight: bold; color: #d16baf;">--</div>
            </div>
            
            <button type="button" class="btn btn-success" style="width: 100%;" onclick="loadCategories()">📂 Load Categories</button>
        </div>
        
        <div class="card" style="margin-top: 20px;">
            <div class="card-title">Categories List</div>
            <div id="categoriesContainer" style="max-height: 600px; overflow-y: auto;">
                <p style="text-align: center; color: #999;">Click "Load Categories" to see your categories</p>
            </div>
        </div>
    </div>
    
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Category SEO Tips</div>
            <ul style="list-style: disc; margin-left: 20px; line-height: 1.8;">
                <li>Use descriptive category names</li>
                <li>Write unique category descriptions</li>
                <li>Add meta descriptions for each category</li>
                <li>Use proper category URLs (URL-friendly)</li>
                <li>Add breadcrumb navigation</li>
                <li>Include category images/thumbnails</li>
                <li>Link categories to related content</li>
            </ul>
        </div>
    </div>
HTML;
}

function render_seo_homepage() {
    global $seo_plugin;
    
    $seo_data = $seo_plugin->getSEOData('homepage', 1) ?? [];
    
    $title = $seo_data['title'] ?? '';
    $meta_description = $seo_data['meta_description'] ?? '';
    $focus_keyword = $seo_data['focus_keyword'] ?? '';
    $og_title = $seo_data['og_title'] ?? '';
    $og_description = $seo_data['og_description'] ?? '';
    $og_image = $seo_data['og_image'] ?? '';
    
    echo <<<HTML
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Homepage SEO</div>
            <form id="homepageSEOForm" onsubmit="savePageSEO('homepage', 1); return false;">
                <input type="hidden" name="page_type" value="homepage">
                <input type="hidden" name="page_id" value="1">
                
                <div class="form-group">
                    <label>Page Title</label>
                    <input type="text" name="title" value="$title" placeholder="Homepage title (30-60 chars)">
                    <div class="char-count"><span id="homeTitleCount">0</span>/60</div>
                </div>
                
                <div class="form-group">
                    <label>Meta Description</label>
                    <textarea name="meta_description" placeholder="Meta description (120-160 chars)">$meta_description</textarea>
                    <div class="char-count"><span id="homeDescCount">0</span>/160</div>
                </div>
                
                <div class="form-group">
                    <label>Focus Keyword</label>
                    <input type="text" name="focus_keyword" value="$focus_keyword" placeholder="Main keyword">
                </div>
                
                <button type="submit" class="btn btn-success" style="width: 100%;">💾 Save Homepage SEO</button>
            </form>
        </div>
        
        <div class="card">
            <div class="card-title">Open Graph Tags</div>
            <form onsubmit="return false;">
                <div class="form-group">
                    <label>OG Title</label>
                    <input type="text" value="$og_title" placeholder="Homepage OG title">
                </div>
                
                <div class="form-group">
                    <label>OG Description</label>
                    <textarea placeholder="Homepage OG description">$og_description</textarea>
                </div>
                
                <div class="form-group">
                    <label>OG Image URL</label>
                    <input type="url" value="$og_image" placeholder="https://example.com/image.jpg">
                </div>
                
                <button type="button" class="btn btn-success" style="width: 100%;">💾 Save OG Tags</button>
            </form>
        </div>
    </div>
HTML;
}

function render_seo_about() {
    global $seo_plugin;
    
    $seo_data = $seo_plugin->getSEOData('about', 1) ?? [];
    
    $title = $seo_data['title'] ?? '';
    $meta_description = $seo_data['meta_description'] ?? '';
    $focus_keyword = $seo_data['focus_keyword'] ?? '';
    
    echo <<<HTML
    <div class="grid-2">
        <div class="card">
            <div class="card-title">About Page SEO</div>
            <form id="aboutSEOForm" onsubmit="savePageSEO('about', 1); return false;">
                <input type="hidden" name="page_type" value="about">
                <input type="hidden" name="page_id" value="1">
                
                <div class="form-group">
                    <label>Page Title</label>
                    <input type="text" name="title" value="$title" placeholder="About page title (30-60 chars)">
                    <div class="char-count"><span id="aboutTitleCount">0</span>/60</div>
                </div>
                
                <div class="form-group">
                    <label>Meta Description</label>
                    <textarea name="meta_description" placeholder="Meta description (120-160 chars)">$meta_description</textarea>
                    <div class="char-count"><span id="aboutDescCount">0</span>/160</div>
                </div>
                
                <div class="form-group">
                    <label>Focus Keyword</label>
                    <input type="text" name="focus_keyword" value="$focus_keyword" placeholder="Main keyword">
                </div>
                
                <button type="submit" class="btn btn-success" style="width: 100%;">💾 Save About SEO</button>
            </form>
        </div>
        
        <div class="card">
            <div class="card-title">About Page Guidelines</div>
            <ul style="list-style: disc; margin-left: 20px; line-height: 1.8;">
                <li>Write compelling company story</li>
                <li>Include company mission and values</li>
                <li>Add team member information</li>
                <li>Include company achievements</li>
                <li>Add trust signals (certifications, awards)</li>
                <li>Include company contact information</li>
                <li>Add internal links to relevant pages</li>
            </ul>
        </div>
    </div>
HTML;
}

function render_seo_contact() {
    global $seo_plugin;
    
    $seo_data = $seo_plugin->getSEOData('contact', 1) ?? [];
    
    $title = $seo_data['title'] ?? '';
    $meta_description = $seo_data['meta_description'] ?? '';
    $focus_keyword = $seo_data['focus_keyword'] ?? '';
    
    echo <<<HTML
    <div class="grid-2">
        <div class="card">
            <div class="card-title">Contact Page SEO</div>
            <form id="contactSEOForm" onsubmit="savePageSEO('contact', 1); return false;">
                <input type="hidden" name="page_type" value="contact">
                <input type="hidden" name="page_id" value="1">
                
                <div class="form-group">
                    <label>Page Title</label>
                    <input type="text" name="title" value="$title" placeholder="Contact page title (30-60 chars)">
                    <div class="char-count"><span id="contactTitleCount">0</span>/60</div>
                </div>
                
                <div class="form-group">
                    <label>Meta Description</label>
                    <textarea name="meta_description" placeholder="Meta description (120-160 chars)">$meta_description</textarea>
                    <div class="char-count"><span id="contactDescCount">0</span>/160</div>
                </div>
                
                <div class="form-group">
                    <label>Focus Keyword</label>
                    <input type="text" name="focus_keyword" value="$focus_keyword" placeholder="Main keyword">
                </div>
                
                <button type="submit" class="btn btn-success" style="width: 100%;">💾 Save Contact SEO</button>
            </form>
        </div>
        
        <div class="card">
            <div class="card-title">Contact Page Tips</div>
            <ul style="list-style: disc; margin-left: 20px; line-height: 1.8;">
                <li>Include clear contact information</li>
                <li>Add contact form with proper labels</li>
                <li>Include business hours</li>
                <li>Add location information/map</li>
                <li>Include multiple contact methods</li>
                <li>Add schema markup for organization</li>
                <li>Ensure fast page load times</li>
            </ul>
        </div>
    </div>
HTML;
}


// Output the page HTML
ob_end_flush();


?>
