<?php
/**
 * SEO System Initialization & Setup
 * Initialize database, test all components, and validate setup
 */

session_start();

// Check admin authentication
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;
}

require_once 'db_config.php';
require_once 'seo_db_schema.php';
require_once 'seo_plugin.php';
require_once 'seo_analytics.php';
require_once 'seo_site_auditor.php';
require_once 'seo_schema_generator.php';

// Use the connection from db_config.php
$db = $conn;  // Already initialized in db_config.php

if ($db->connect_error) {
    die('Database connection failed: ' . $db->connect_error);
}

// Handle initialization requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['init_action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['init_action']) {
        case 'init_database':
            $schema = new SEODatabaseSchema($db);
            if ($schema->initializeAllTables()) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Database schema initialized successfully',
                    'status' => 'completed'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error: ' . $db->error
                ]);
            }
            exit;
            
        case 'test_components':
            $results = testAllComponents($db, $db_config);
            echo json_encode($results);
            exit;
            
        case 'generate_sample_data':
            generateSampleData($db);
            echo json_encode(['success' => true, 'message' => 'Sample data generated']);
            exit;
    }
}

function testAllComponents($db, $db_config) {
    $results = [];
    
    // Test SEO Plugin
    try {
        $plugin = new SEOPlugin($db_config);
        $results['seo_plugin'] = ['status' => 'OK', 'message' => 'SEOPlugin loaded successfully'];
    } catch (Exception $e) {
        $results['seo_plugin'] = ['status' => 'ERROR', 'message' => $e->getMessage()];
    }
    
    // Test SEO Analytics
    try {
        $analytics = new SEOAnalytics($db);
        $results['seo_analytics'] = ['status' => 'OK', 'message' => 'SEOAnalytics loaded successfully'];
    } catch (Exception $e) {
        $results['seo_analytics'] = ['status' => 'ERROR', 'message' => $e->getMessage()];
    }
    
    // Test Schema Generator
    try {
        $schema = SchemaMarkupGenerator::generateSchema('article', [
            'title' => 'Test Article',
            'description' => 'Test description',
            'url' => 'http://test.local/test'
        ]);
        $results['schema_generator'] = ['status' => 'OK', 'message' => 'Schema generation working'];
    } catch (Exception $e) {
        $results['schema_generator'] = ['status' => 'ERROR', 'message' => $e->getMessage()];
    }
    
    // Test Site Auditor
    try {
        $results['site_auditor'] = ['status' => 'OK', 'message' => 'SiteAuditor class loaded successfully'];
    } catch (Exception $e) {
        $results['site_auditor'] = ['status' => 'ERROR', 'message' => $e->getMessage()];
    }
    
    // Test Database Tables
    $tables_to_check = ['seo_meta', 'seo_analytics', 'seo_audit', 'seo_schema', 'seo_keywords', 'seo_siteurl'];
    $tables = [];
    
    foreach ($tables_to_check as $table) {
        $check = $db->query("SHOW TABLES LIKE '$table'");
        $tables[$table] = $check && $check->num_rows > 0 ? 'EXISTS' : 'MISSING';
    }
    
    $results['database_tables'] = $tables;
    
    return $results;
}

function generateSampleData($db) {
    // Sample SEO meta data
    $sample_seo = [
        [
            'entity_type' => 'product',
            'entity_id' => 1,
            'focus_keyword' => 'best product online',
            'seo_title' => 'Best Product Online | Quality & Affordable',
            'meta_desc' => 'Discover our best products online with high quality and affordable prices. Free shipping on orders over $50.',
            'canonical_url' => 'https://example.com/product1',
            'is_noindex' => 0,
            'seo_score' => 85
        ]
    ];
    
    $stmt = $db->prepare("INSERT INTO seo_meta 
        (entity_type, entity_id, focus_keyword, seo_title, meta_desc, canonical_url, is_noindex, seo_score)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE seo_score = VALUES(seo_score)");
    
    foreach ($sample_seo as $data) {
        $stmt->bind_param('ssssssis',
            $data['entity_type'],
            $data['entity_id'],
            $data['focus_keyword'],
            $data['seo_title'],
            $data['meta_desc'],
            $data['canonical_url'],
            $data['is_noindex'],
            $data['seo_score']
        );
        $stmt->execute();
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SEO System Setup - Admin Panel</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .setup-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 600px;
            width: 100%;
            padding: 40px;
        }
        
        .setup-header {
            text-align: center;
            margin-bottom: 40px;
        }
        
        .setup-header h1 {
            font-size: 28px;
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        .setup-header p {
            color: #7f8c8d;
            font-size: 14px;
        }
        
        .setup-step {
            margin-bottom: 30px;
        }
        
        .step-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .step-icon {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }
        
        .step-icon.pending {
            background: #e9ecef;
            color: #7f8c8d;
        }
        
        .step-icon.loading {
            background: #ffc107;
            color: #fff;
            animation: spin 1s linear infinite;
        }
        
        .step-icon.success {
            background: #28a745;
            color: white;
        }
        
        .step-icon.error {
            background: #dc3545;
            color: white;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .step-button {
            padding: 12px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .step-button:hover {
            background: #764ba2;
        }
        
        .step-button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .step-status {
            font-size: 13px;
            color: #7f8c8d;
            margin-top: 8px;
        }
        
        .step-status.success {
            color: #28a745;
        }
        
        .step-status.error {
            color: #dc3545;
        }
        
        .results-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
            margin-top: 10px;
        }
        
        .results-table th {
            background: #f8f9fa;
            padding: 10px;
            text-align: left;
            font-weight: 600;
            border-bottom: 1px solid #ddd;
            color: #2c3e50;
        }
        
        .results-table td {
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-success {
            background: #d4edda;
            color: #155724;
        }
        
        .badge-error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .badge-warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .completion-message {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 6px;
            margin-top: 20px;
            display: none;
        }
        
        .completion-message.show {
            display: block;
        }
        
        .next-button {
            margin-top: 20px;
            width: 100%;
            padding: 12px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 16px;
            display: none;
        }
        
        .next-button.show {
            display: block;
        }
        
        .next-button:hover {
            background: #218838;
        }
    </style>
</head>
<body>
    <div class="setup-container">
        <div class="setup-header">
            <h1> SEO System Setup</h1>
            <p>Initialize your Yoast-style SEO engine for e-commerce</p>
        </div>
        
        <!-- Step 1: Database Initialization -->
        <div class="setup-step">
            <div class="step-title">
                <div class="step-icon pending" id="step1-icon">1</div>
                <span>Initialize Database Schema</span>
            </div>
            <button class="step-button" id="init-db-btn" onclick="initDatabase()">Initialize Database</button>
            <div class="step-status" id="step1-status"></div>
        </div>
        
        <!-- Step 2: Component Testing -->
        <div class="setup-step">
            <div class="step-title">
                <div class="step-icon pending" id="step2-icon">2</div>
                <span>Test System Components</span>
            </div>
            <button class="step-button" id="test-btn" onclick="testComponents()" disabled>Test Components</button>
            <div class="step-status" id="step2-status"></div>
            <table class="results-table" id="results-table" style="display: none;">
                <thead>
                    <tr>
                        <th>Component</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody id="results-tbody"></tbody>
            </table>
        </div>
        
        <!-- Step 3: Generate Sample Data -->
        <div class="setup-step">
            <div class="step-title">
                <div class="step-icon pending" id="step3-icon">3</div>
                <span>Generate Sample Data</span>
            </div>
            <button class="step-button" id="sample-btn" onclick="generateSampleData()" disabled>Generate Sample Data</button>
            <div class="step-status" id="step3-status"></div>
        </div>
        
        <!-- Completion Message -->
        <div class="completion-message" id="completion-message">
            <strong>✓ SEO System Setup Complete!</strong>
            <p>Your Yoast-style SEO engine is now fully operational. Start using it from the SEO Manager dashboard.</p>
        </div>
        
        <button class="next-button" id="next-btn" onclick="redirectToDashboard()">Go to SEO Manager</button>
    </div>
    
    <script>
        let completedSteps = 0;
        
        async function initDatabase() {
            const btn = document.getElementById('init-db-btn');
            const icon = document.getElementById('step1-icon');
            const status = document.getElementById('step1-status');
            const testBtn = document.getElementById('test-btn');
            
            btn.disabled = true;
            icon.className = 'step-icon loading';
            icon.textContent = '⏳';
            status.textContent = 'Initializing...';
            
            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'init_action=init_database'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    icon.className = 'step-icon success';
                    icon.textContent = '✓';
                    status.className = 'step-status success';
                    status.textContent = 'Database schema initialized successfully';
                    testBtn.disabled = false;
                    completedSteps++;
                } else {
                    icon.className = 'step-icon error';
                    icon.textContent = '✕';
                    status.className = 'step-status error';
                    status.textContent = data.message;
                }
            } catch (error) {
                console.error(error);
                icon.className = 'step-icon error';
                icon.textContent = '✕';
                status.className = 'step-status error';
                status.textContent = 'Error: ' + error.message;
            }
        }
        
        async function testComponents() {
            const btn = document.getElementById('test-btn');
            const icon = document.getElementById('step2-icon');
            const status = document.getElementById('step2-status');
            const sampleBtn = document.getElementById('sample-btn');
            
            btn.disabled = true;
            icon.className = 'step-icon loading';
            icon.textContent = '⏳';
            status.textContent = 'Testing components...';
            
            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'init_action=test_components'
                });
                
                const data = await response.json();
                
                // Display results
                const tbody = document.getElementById('results-tbody');
                tbody.innerHTML = '';
                let allSuccess = true;
                
                for (const [component, result] of Object.entries(data)) {
                    if (component === 'database_tables') {
                        for (const [table, status] of Object.entries(result)) {
                            const row = `
                                <tr>
                                    <td>${table}</td>
                                    <td><span class="badge ${status === 'EXISTS' ? 'badge-success' : 'badge-error'}">${status}</span></td>
                                </tr>
                            `;
                            tbody.innerHTML += row;
                            if (status !== 'EXISTS') allSuccess = false;
                        }
                    } else {
                        const row = `
                            <tr>
                                <td>${component}</td>
                                <td><span class="badge ${result.status === 'OK' ? 'badge-success' : 'badge-error'}">${result.status}</span></td>
                            </tr>
                        `;
                        tbody.innerHTML += row;
                        if (result.status !== 'OK') allSuccess = false;
                    }
                }
                
                document.getElementById('results-table').style.display = 'table';
                
                if (allSuccess) {
                    icon.className = 'step-icon success';
                    icon.textContent = '✓';
                    status.className = 'step-status success';
                    status.textContent = 'All components working correctly';
                    sampleBtn.disabled = false;
                    completedSteps++;
                } else {
                    icon.className = 'step-icon error';
                    icon.textContent = '✕';
                    status.className = 'step-status error';
                    status.textContent = 'Some components have issues';
                }
            } catch (error) {
                console.error(error);
                icon.className = 'step-icon error';
                icon.textContent = '✕';
                status.className = 'step-status error';
                status.textContent = 'Error: ' + error.message;
            }
        }
        
        async function generateSampleData() {
            const btn = document.getElementById('sample-btn');
            const icon = document.getElementById('step3-icon');
            const status = document.getElementById('step3-status');
            
            btn.disabled = true;
            icon.className = 'step-icon loading';
            icon.textContent = '⏳';
            status.textContent = 'Generating sample data...';
            
            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'init_action=generate_sample_data'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    icon.className = 'step-icon success';
                    icon.textContent = '✓';
                    status.className = 'step-status success';
                    status.textContent = 'Sample data generated successfully';
                    completedSteps++;
                    
                    // Show completion message and next button
                    document.getElementById('completion-message').classList.add('show');
                    document.getElementById('next-btn').classList.add('show');
                } else {
                    icon.className = 'step-icon error';
                    icon.textContent = '✕';
                    status.className = 'step-status error';
                    status.textContent = data.message;
                }
            } catch (error) {
                console.error(error);
                icon.className = 'step-icon error';
                icon.textContent = '✕';
                status.className = 'step-status error';
                status.textContent = 'Error: ' + error.message;
            }
        }
        
        function redirectToDashboard() {
            window.location.href = 'admin_seo_manager.php?action=dashboard';
        }
    </script>
</body>
</html>
