<?php
$configFile   = __DIR__ . '/../../../config/database.php';
$config       = require $configFile;
$currentDriver = $config['driver'] ?? 'json';
$mysql         = $config['mysql'] ?? [];

$message = '';
$msgType = '';

// ─── Handle Form Posts ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Save connection settings
    if (isset($_POST['action']) && $_POST['action'] === 'save_config') {
        $driver   = $_POST['driver'] ?? 'json';
        $newConf  = [
            'driver' => $driver,
            'mysql'  => [
                'host'     => trim($_POST['mysql_host']     ?? 'localhost'),
                'port'     => (int)($_POST['mysql_port']    ?? 3306),
                'database' => trim($_POST['mysql_database'] ?? 'everest'),
                'username' => trim($_POST['mysql_username'] ?? 'root'),
                'password' => trim($_POST['mysql_password'] ?? ''),
                'charset'  => 'utf8mb4',
                'prefix'   => trim($_POST['mysql_prefix']   ?? ''),
            ],
        ];

        $phpContent = "<?php\nreturn " . var_export($newConf, true) . ";\n";
        if (file_put_contents($configFile, $phpContent) !== false) {
            $config        = $newConf;
            $currentDriver = $driver;
            $mysql         = $newConf['mysql'];
            $message = 'Ayarlar kaydedildi.';
            $msgType = 'success';
        } else {
            $message = 'Ayarlar kaydedilemedi. config/database.php yazma iznini kontrol edin.';
            $msgType = 'error';
        }
    }

    // Test MySQL connection
    if (isset($_POST['action']) && $_POST['action'] === 'test_connection') {
        $host   = trim($_POST['mysql_host']     ?? 'localhost');
        $port   = (int)($_POST['mysql_port']    ?? 3306);
        $db     = trim($_POST['mysql_database'] ?? 'everest');
        $user   = trim($_POST['mysql_username'] ?? 'root');
        $pass   = trim($_POST['mysql_password'] ?? '');
        try {
            $pdo = new PDO("mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4", $user, $pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_TIMEOUT => 5,
            ]);
            $ver = $pdo->query('SELECT VERSION()')->fetchColumn();
            $message = "Bağlantı başarılı! MySQL sürümü: {$ver}";
            $msgType = 'success';
        } catch (\Exception $e) {
            $message = 'Bağlantı hatası: ' . $e->getMessage();
            $msgType = 'error';
        }
    }

    // Run migration: JSON → MySQL
    if (isset($_POST['action']) && $_POST['action'] === 'migrate') {
        try {
            $migrConfig = require $configFile;
            $mysql = $migrConfig['mysql'];
            $pdo = new PDO(
                "mysql:host={$mysql['host']};port={$mysql['port']};dbname={$mysql['database']};charset=utf8mb4",
                $mysql['username'],
                $mysql['password'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );

            // Create tables
            $schema = file_get_contents(__DIR__ . '/../../../../config/schema.sql');
            foreach (explode(';', $schema) as $stmt) {
                $stmt = trim($stmt);
                if ($stmt) {
                    $pdo->exec($stmt);
                }
            }

            // Migrate JSON data
            $tenantId = defined('TENANT_ID') ? TENANT_ID : 'everestburo';
            $dataDir  = __DIR__ . '/../../../../data/tenants/' . $tenantId;
            $tables   = ['products', 'categories', 'orders', 'users', 'pages', 'tenants'];
            $jsonColumns = ['images', 'categories', 'specs', 'tags', 'meta'];
            $stats = [];

            foreach ($tables as $table) {
                $file = $dataDir . '/' . $table . '.json';
                if (!file_exists($file)) {
                    $stats[$table] = 0;
                    continue;
                }
                $rows = json_decode(file_get_contents($file), true) ?: [];
                $count = 0;

                foreach ($rows as $row) {
                    // Check if already exists
                    $exists = $pdo->prepare("SELECT id FROM `{$table}` WHERE id = ?");
                    $exists->execute([$row['id']]);
                    if ($exists->fetchColumn()) continue;

                    // Encode JSON columns
                    foreach ($jsonColumns as $col) {
                        if (isset($row[$col]) && is_array($row[$col])) {
                            $row[$col] = json_encode($row[$col], JSON_UNESCAPED_UNICODE);
                        }
                    }

                    // Get actual columns for this table
                    $cols  = array_keys($row);
                    $info  = $pdo->query("DESCRIBE `{$table}`")->fetchAll(PDO::FETCH_COLUMN);
                    $valid = array_intersect($cols, $info);
                    if (empty($valid)) continue;

                    $vals  = array_map(fn($c) => $row[$c], $valid);
                    $sql   = "INSERT IGNORE INTO `{$table}` (`" . implode('`,`', $valid) . "`) VALUES (" . implode(',', array_fill(0, count($valid), '?')) . ")";
                    $stmt  = $pdo->prepare($sql);
                    $stmt->execute($vals);
                    $count++;
                }
                $stats[$table] = $count;
            }

            $summary = implode(', ', array_map(fn($t, $n) => "{$t}: {$n}", array_keys($stats), $stats));
            $message = "Migrasyon tamamlandı! {$summary}";
            $msgType = 'success';
        } catch (\Exception $e) {
            $message = 'Migrasyon hatası: ' . $e->getMessage();
            $msgType = 'error';
        }
    }
}
?>
<?php include __DIR__ . '/layout/header.php'; ?>

<style>
.db-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
.db-card { background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 24px; }
.db-card h3 { font-size: 15px; font-weight: 700; margin: 0 0 18px; display: flex; align-items: center; gap: 8px; }
.driver-toggle { display: flex; gap: 12px; margin-bottom: 20px; }
.driver-btn { flex: 1; padding: 12px; border: 2px solid var(--border); border-radius: var(--r-md); cursor: pointer; text-align: center; font-weight: 600; background: var(--surface-3); color: var(--text-2); transition: all 0.2s; }
.driver-btn.active { border-color: var(--primary); background: var(--primary); color: #fff; }
.db-field { margin-bottom: 14px; }
.db-field label { display: block; font-size: 12px; font-weight: 600; color: var(--text-2); margin-bottom: 5px; }
.db-field input { width: 100%; padding: 9px 12px; background: var(--surface-3); border: 1px solid var(--border); border-radius: var(--r-sm); color: var(--text-1); font-size: 14px; box-sizing: border-box; }
.status-badge { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 20px; font-size: 13px; font-weight: 600; }
.badge-json { background: #f97316/15; color: #f97316; border: 1px solid #f97316; }
.badge-mysql { background: #10b981/15; color: #10b981; border: 1px solid #10b981; }
.migrate-box { background: linear-gradient(135deg, var(--surface-2), var(--surface-3)); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 28px; text-align: center; margin-top: 24px; }
.migrate-box h3 { font-size: 16px; font-weight: 700; margin: 0 0 10px; }
.migrate-box p { font-size: 13px; color: var(--text-2); margin: 0 0 20px; max-width: 500px; margin-left: auto; margin-right: auto; }
.btn-migrate { background: linear-gradient(135deg, #8b5cf6, #6d28d9); color: #fff; border: none; padding: 12px 28px; border-radius: var(--r-md); font-size: 15px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; }
.btn-migrate:hover { opacity: 0.9; }
.alert { padding: 14px 18px; border-radius: var(--r-md); margin-bottom: 20px; display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 14px; }
.alert-success { background: #10b98120; color: #10b981; border: 1px solid #10b981; }
.alert-error { background: #ef444420; color: #ef4444; border: 1px solid #ef4444; }
@media(max-width:768px) { .db-grid { grid-template-columns: 1fr; } }
</style>

<div class="admin-card">
    <div class="admin-card-header" style="margin-bottom: 24px;">
        <h2 style="font-size: 18px; font-weight: 700; margin: 0;">
            <i class="fa fa-database" style="color: var(--primary); margin-right: 8px;"></i>
            Veritabanı Yönetimi
        </h2>
        <div style="margin-top: 8px; display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 13px; color: var(--text-2);">Aktif sürücü:</span>
            <?php if ($currentDriver === 'mysql'): ?>
                <span class="status-badge" style="background: #10b98120; color: #10b981; border: 1px solid #10b981;">
                    <i class="fa fa-database"></i> MySQL
                </span>
            <?php else: ?>
                <span class="status-badge" style="background: #f9731620; color: #f97316; border: 1px solid #f97316;">
                    <i class="fa fa-file-text-o"></i> JSON Dosya
                </span>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $msgType; ?>">
            <i class="fa fa-<?php echo $msgType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <form method="POST">
        <input type="hidden" name="action" value="save_config">
        <div class="db-grid">
            <!-- Left: Driver Selection -->
            <div class="db-card">
                <h3><i class="fa fa-toggle-on"></i> Sürücü Seçimi</h3>

                <div class="driver-toggle">
                    <label class="driver-btn <?php echo $currentDriver === 'json' ? 'active' : ''; ?>" onclick="setDriver('json')">
                        <i class="fa fa-file-text-o"></i><br>
                        <span>JSON (Dosya)</span>
                    </label>
                    <label class="driver-btn <?php echo $currentDriver === 'mysql' ? 'active' : ''; ?>" onclick="setDriver('mysql')">
                        <i class="fa fa-database"></i><br>
                        <span>MySQL</span>
                    </label>
                </div>
                <input type="hidden" name="driver" id="driver_input" value="<?php echo htmlspecialchars($currentDriver); ?>">

                <div style="background: var(--surface-3); border-radius: var(--r-md); padding: 14px; font-size: 13px; color: var(--text-2); line-height: 1.6;">
                    <strong style="color: var(--text-1);">JSON:</strong> Kurulum gerektirmez. Küçük veri setleri için idealdir.<br><br>
                    <strong style="color: var(--text-1);">MySQL:</strong> Büyük veri, eş zamanlı erişim ve gelişmiş arama için uygundur.
                </div>
            </div>

            <!-- Right: MySQL Settings -->
            <div class="db-card" id="mysql_settings" style="<?php echo $currentDriver !== 'mysql' ? 'opacity:0.5;' : ''; ?>">
                <h3><i class="fa fa-server"></i> MySQL Bağlantı Bilgileri</h3>

                <div class="db-field">
                    <label>Sunucu (Host)</label>
                    <input type="text" name="mysql_host" value="<?php echo htmlspecialchars($mysql['host'] ?? 'localhost'); ?>">
                </div>
                <div style="display:grid; grid-template-columns: 2fr 1fr; gap:10px;">
                    <div class="db-field">
                        <label>Veritabanı Adı</label>
                        <input type="text" name="mysql_database" value="<?php echo htmlspecialchars($mysql['database'] ?? 'everest'); ?>">
                    </div>
                    <div class="db-field">
                        <label>Port</label>
                        <input type="number" name="mysql_port" value="<?php echo htmlspecialchars($mysql['port'] ?? 3306); ?>">
                    </div>
                </div>
                <div class="db-field">
                    <label>Kullanıcı Adı</label>
                    <input type="text" name="mysql_username" value="<?php echo htmlspecialchars($mysql['username'] ?? 'root'); ?>" autocomplete="off">
                </div>
                <div class="db-field">
                    <label>Şifre</label>
                    <input type="password" name="mysql_password" value="<?php echo htmlspecialchars($mysql['password'] ?? ''); ?>" autocomplete="new-password">
                </div>
                <div class="db-field">
                    <label>Tablo Ön Eki (Opsiyonel)</label>
                    <input type="text" name="mysql_prefix" value="<?php echo htmlspecialchars($mysql['prefix'] ?? ''); ?>" placeholder="örn: ev_">
                </div>

                <button type="submit" formaction="" name="action" value="test_connection"
                        style="background: var(--surface-3); border: 1px solid var(--border); color: var(--text-1); padding: 8px 16px; border-radius: var(--r-sm); cursor: pointer; font-size: 13px; font-weight: 600;">
                    <i class="fa fa-plug"></i> Bağlantıyı Test Et
                </button>
            </div>
        </div>

        <div style="text-align: right; margin-top: 20px;">
            <button type="submit" class="admin-btn admin-btn-primary">
                <i class="fa fa-save"></i> Ayarları Kaydet
            </button>
        </div>
    </form>

    <!-- Migration Box -->
    <div class="migrate-box">
        <i class="fa fa-exchange" style="font-size: 32px; color: #8b5cf6; margin-bottom: 12px; display: block;"></i>
        <h3>JSON → MySQL Veri Aktarımı</h3>
        <p>
            Mevcut JSON dosyalarındaki tüm verileri (ürünler, kategoriler, siparişler, kullanıcılar, sayfalar)
            MySQL veritabanına aktarır. Tablolar otomatik oluşturulur. Aktarım güvenlidir — mevcut kayıtları atlayarak
            sadece eksik olanları ekler.
        </p>
        <form method="POST" onsubmit="return confirm('JSON verilerini MySQL\'e aktarmak istediğinizden emin misiniz?')">
            <input type="hidden" name="action" value="migrate">
            <button type="submit" class="btn-migrate">
                <i class="fa fa-database"></i>
                Aktarımı Başlat
            </button>
        </form>
        <p style="margin-top: 14px; font-size: 12px; color: var(--text-3);">
            Not: Aktarım öncesinde MySQL bağlantı bilgilerini kaydetmeyi ve test etmeyi unutmayın.
        </p>
    </div>
</div>

<script>
function setDriver(val) {
    document.getElementById('driver_input').value = val;
    document.querySelectorAll('.driver-btn').forEach(b => b.classList.remove('active'));
    event.currentTarget.classList.add('active');
    document.getElementById('mysql_settings').style.opacity = val === 'mysql' ? '1' : '0.5';
}
</script>

<?php include __DIR__ . '/layout/footer.php'; ?>
