<?php
/**
 * Simple Database Initialization - No Session Dependencies
 * This file initializes the SEO database tables directly
 */

// Don't start session - let the parent handle it
// Just directly initialize the database

require_once 'seo_plugin.php';

// Database configuration
$db_config = [
    'host' => 'localhost',
    'user' => 'root',
    'password' => '',
    'database' => 'login-table'
];

// Create database connection
$conn = new mysqli(
    $db_config['host'],
    $db_config['user'],
    $db_config['password'],
    $db_config['database']
);

if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed: ' . $conn->connect_error]));
}

$conn->set_charset('utf8mb4');

// Initialize SEO tables directly
try {
    // Create SEO Settings Table
    $sql_seo = "CREATE TABLE IF NOT EXISTS seo_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        page_type VARCHAR(50) NOT NULL,
        page_id INT,
        title VARCHAR(255) NOT NULL,
        meta_description TEXT,
        meta_keywords TEXT,
        focus_keyword VARCHAR(255),
        slug VARCHAR(255) UNIQUE,
        canonical_url VARCHAR(255),
        robots_meta VARCHAR(100),
        og_title VARCHAR(255),
        og_description TEXT,
        og_image VARCHAR(255),
        twitter_title VARCHAR(255),
        twitter_description TEXT,
        twitter_image VARCHAR(255),
        readability_score INT DEFAULT 0,
        keyword_density FLOAT DEFAULT 0,
        keyword_rank INT DEFAULT 0,
        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),
        INDEX idx_page_type (page_type),
        INDEX idx_created_at (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if (!$conn->query($sql_seo)) {
        throw new Exception("Error creating seo_settings table: " . $conn->error);
    }
    
    // Create Analytics Table
    $sql_analytics = "CREATE TABLE IF NOT EXISTS seo_analytics (
        id INT AUTO_INCREMENT PRIMARY KEY,
        seo_id INT,
        page_type VARCHAR(50),
        impressions INT DEFAULT 0,
        clicks INT DEFAULT 0,
        avg_position FLOAT DEFAULT 0,
        ctr FLOAT DEFAULT 0,
        bounce_rate FLOAT DEFAULT 0,
        avg_session_duration INT DEFAULT 0,
        conversion_rate FLOAT DEFAULT 0,
        top_keywords TEXT,
        traffic_source VARCHAR(100),
        date DATE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_analytics (seo_id, date),
        INDEX idx_date (date),
        INDEX idx_page_type (page_type),
        FOREIGN KEY (seo_id) REFERENCES seo_settings(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if (!$conn->query($sql_analytics)) {
        throw new Exception("Error creating seo_analytics table: " . $conn->error);
    }
    
    // Insert sample data
    $sample_pages = [
        ['Home Page', 'homepage', 'homepage', 'home'],
        ['Products', 'products', 'products', 'products'],
        ['Blog', 'blog', 'blog', 'blog']
    ];
    
    foreach ($sample_pages as $page) {
        $title = $conn->real_escape_string($page[0]);
        $page_type = $page[1];
        $slug = $page[3];
        
        $check = $conn->query("SELECT id FROM seo_settings WHERE slug = '$slug' LIMIT 1");
        if ($check->num_rows === 0) {
            $insert = "INSERT INTO seo_settings (page_type, page_id, title, slug, meta_description, focus_keyword)
                      VALUES ('$page_type', 1, '$title', '$slug', 'Sample $title', '$page_type')";
            $conn->query($insert);
        }
    }
    
    $conn->close();
    
    // Return success response
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['json'])) {
        echo json_encode(['success' => true, 'message' => 'Database initialized successfully!']);
    } else {
        // Return HTML response
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>SEO Manager - Database Initialized</title>
            <style>
                body { 
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    min-height: 100vh;
                    margin: 0;
                    padding: 20px;
                }
                .container {
                    background: white;
                    border-radius: 10px;
                    padding: 40px;
                    max-width: 500px;
                    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                    text-align: center;
                }
                .success {
                    color: #10b981;
                    font-size: 50px;
                    margin-bottom: 20px;
                }
                h1 {
                    color: #333;
                    margin: 0 0 10px 0;
                }
                p {
                    color: #666;
                    font-size: 16px;
                    line-height: 1.6;
                }
                .message {
                    background: #ecfdf5;
                    border: 2px solid #10b981;
                    border-radius: 8px;
                    padding: 20px;
                    margin: 20px 0;
                    color: #065f46;
                }
                .btn {
                    display: inline-block;
                    background: #667eea;
                    color: white;
                    padding: 12px 30px;
                    border-radius: 6px;
                    text-decoration: none;
                    font-weight: 500;
                    margin-top: 20px;
                }
                .btn:hover {
                    background: #764ba2;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="success">✅</div>
                <h1>Database Initialized!</h1>
                <div class="message">
                    <p>SEO Manager database tables have been created successfully!</p>
                    <p>Sample data (Home, Products, Blog) has been added.</p>
                </div>
                <p>You can now access the SEO Manager and start optimizing your pages.</p>
                <a href="admin_seo_manager.php" class="btn">Go to SEO Manager →</a>
            </div>
        </body>
        </html>
        <?php
    }
    
} catch (Exception $e) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['json'])) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    } else {
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>SEO Manager - Initialization Error</title>
            <style>
                body { 
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    min-height: 100vh;
                    margin: 0;
                    padding: 20px;
                }
                .container {
                    background: white;
                    border-radius: 10px;
                    padding: 40px;
                    max-width: 500px;
                    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                    text-align: center;
                }
                .error {
                    color: #ef4444;
                    font-size: 50px;
                    margin-bottom: 20px;
                }
                h1 {
                    color: #333;
                    margin: 0 0 10px 0;
                }
                .message {
                    background: #fef2f2;
                    border: 2px solid #ef4444;
                    border-radius: 8px;
                    padding: 20px;
                    margin: 20px 0;
                    color: #7f1d1d;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="error">❌</div>
                <h1>Initialization Error</h1>
                <div class="message">
                    <p><?php echo htmlspecialchars($e->getMessage()); ?></p>
                </div>
                <p>Please check your database connection and try again.</p>
            </div>
        </body>
        </html>
        <?php
    }
}
?>
