<?php
/**
 * Blog Migration Runner - Execute from browser
 * URL: http://localhost/ecom/run_blog_migration.php
 * 
 * WARNING: This creates blog database tables. 
 * Only run once during initial setup.
 */

session_start();

// Check admin access
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    http_response_code(403);
    die('Access Denied: Admin authentication required');
}

require_once 'db_config.php';

// Use $conn instead of $db (db_config.php defines $conn as $conn)
$db = $conn;

?>
<!DOCTYPE html>
<html>
<head>
    <title>Blog Module Migration</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
        .container { max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        h1 { color: #333; }
        .status { padding: 15px; margin: 20px 0; border-radius: 4px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .warning { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; }
        button { background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background: #0056b3; }
        .table-list { background: #f9f9f9; padding: 15px; border-radius: 4px; margin: 20px 0; }
        .table-list li { margin: 8px 0; }
        pre { background: #f0f0f0; padding: 10px; border-radius: 4px; overflow-x: auto; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📝 Blog Module Database Setup</h1>
        
        <?php
        
        // Check if tables already exist
        $existingTables = [];
        $requiredTables = ['blog_categories', 'blog_tags', 'blogs', 'blog_tag_relations'];
        
        foreach ($requiredTables as $table) {
            $result = $db->query("SHOW TABLES LIKE '$table'");
            if ($result && $result->num_rows > 0) {
                $existingTables[] = $table;
            }
        }
        
        if (count($existingTables) === count($requiredTables)) {
            echo '<div class="status success">';
            echo '<strong>✓ Blog tables already exist!</strong><br>';
            echo 'All required tables are present in your database.<br>';
            echo '<a href="admin_blogs.php" style="color: #155724;">Go to Blog Manager →</a>';
            echo '</div>';
            exit;
        }
        
        if (count($existingTables) > 0 && count($existingTables) < count($requiredTables)) {
            echo '<div class="status warning">';
            echo '<strong>⚠ Partial setup detected</strong><br>';
            echo 'Some blog tables exist but not all. Found: ' . implode(', ', $existingTables) . '<br>';
            echo 'Missing: ' . implode(', ', array_diff($requiredTables, $existingTables)) . '<br><br>';
            echo 'Solution: <a href="clean_blog_tables.php" style="color:#856404; font-weight:bold;">Clean and restart blog setup</a>';
            echo '</div>';
        }
        
        // Load and execute migration
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['execute'])) {
            $sqlFile = __DIR__ . '/migrations/002_create_blog_tables.sql';
            
            if (!file_exists($sqlFile)) {
                echo '<div class="status error">Error: Migration file not found at ' . $sqlFile . '</div>';
                exit;
            }
            
            $sql = file_get_contents($sqlFile);
            $errors = [];
            
            // Execute SQL statements
            if ($db->multi_query($sql)) {
                $tableCount = 0;
                do {
                    if ($result = $db->store_result()) {
                        $result->free();
                    }
                    $tableCount++;
                } while ($db->next_result());
                
                // Verify tables were created
                $verifyCount = 0;
                foreach ($requiredTables as $table) {
                    $result = $db->query("SHOW TABLES LIKE '$table'");
                    if ($result && $result->num_rows > 0) {
                        $verifyCount++;
                    }
                }
                
                if ($verifyCount === count($requiredTables)) {
                    echo '<div class="status success">';
                    echo '<strong>✓ Success! Blog module is ready</strong><br>';
                    echo 'All 4 database tables have been created:<br>';
                    echo '<ul class="table-list">';
                    echo '<li>✓ blog_categories</li>';
                    echo '<li>✓ blog_tags</li>';
                    echo '<li>✓ blogs</li>';
                    echo '<li>✓ blog_tag_relations</li>';
                    echo '</ul>';
                    echo '<a href="admin_blogs.php" style="color: #155724; font-weight: bold;">Proceed to Blog Manager →</a>';
                    echo '</div>';
                    exit;
                } else {
                    echo '<div class="status error">';
                    echo 'Error: Only ' . $verifyCount . ' of ' . count($requiredTables) . ' tables were created.<br>';
                    echo 'Created: ' . implode(', ', array_intersect($requiredTables, $verifyCount ? ['verified'] : []));
                    echo '</div>';
                }
            } else {
                echo '<div class="status error">';
                echo '<strong>Database Error:</strong><br>';
                echo 'Error Code: ' . $db->errno . '<br>';
                echo 'Error Message: ' . htmlspecialchars($db->error);
                echo '</div>';
            }
        }
        
        ?>
        
        <div class="status info">
            <strong>ℹ What this does:</strong><br>
            Creates 4 database tables for the blog module:
            <ul>
                <li><code>blog_categories</code> - Organize blog posts by category</li>
                <li><code>blog_tags</code> - Tag posts for better organization</li>
                <li><code>blogs</code> - Main blog posts table</li>
                <li><code>blog_tag_relations</code> - Links posts to tags</li>
            </ul>
        </div>
        
        <?php if (count($existingTables) < count($requiredTables)): ?>
        <form method="POST" style="text-align: center;">
            <button type="submit" name="execute" value="1" style="padding: 12px 30px; font-size: 18px;">
                ▶ Create Blog Tables Now
            </button>
        </form>
        
        <div class="status warning" style="margin-top: 20px;">
            <strong>First time setup?</strong><br>
            This migration needs to run only once. After clicking the button above, 
            you'll be able to create blog posts from the admin dashboard.
        </div>
        <?php endif; ?>
        
        <hr style="margin-top: 40px;">
        
        <p style="color: #666; font-size: 14px;">
            Admin Panel | 
            <a href="admin_dashboard.php" style="color: #007bff;">Back to Dashboard</a> |
            <a href="admin_blogs.php" style="color: #007bff;">Blog Manager</a>
        </p>
    </div>
</body>
</html>
