<?php
require_once 'auth.php';
require_once __DIR__ . '/../includes/pdo.php';

echo "<h2>🔧 Database Update System</h2>";

try {
    // 1. Add tracking columns to city_service table
    $columns = [
        'content_update_count' => "int(11) NOT NULL DEFAULT 0",
        'is_manually_updated' => "tinyint(1) NOT NULL DEFAULT 0",
        'last_ai_update' => "timestamp NULL DEFAULT NULL"
    ];

    foreach ($columns as $column => $definition) {
        $check = $pdo->query("SHOW COLUMNS FROM city_service LIKE '$column'");
        if ($check->rowCount() == 0) {
            $pdo->exec("ALTER TABLE city_service ADD COLUMN $column $definition");
            echo "<p style='color: green;'>✅ Added column: <strong>$column</strong></p>";
        } else {
            echo "<p style='color: #666;'>ℹ️ Column <strong>$column</strong> already exists.</p>";
        }
    }

    // 2. Create finggu_settings table for API Keys
    $pdo->exec("CREATE TABLE IF NOT EXISTS `finggu_settings` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `setting_key` varchar(100) NOT NULL,
        `setting_value` text,
        `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        UNIQUE KEY `setting_key` (`setting_key`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    echo "<p style='color: green;'>✅ Table <strong>finggu_settings</strong> is ready.</p>";

    echo "<hr><h3>🎉 All database updates completed successfully!</h3>";
    echo "<p><a href='modern-ai-content.php' style='padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 5px;'>Go to AI Content Dashboard</a></p>";

} catch (PDOException $e) {
    die("<p style='color: red;'>❌ Error during database update: " . htmlspecialchars($e->getMessage()) . "</p>");
}
?>
