<?php
/**
 * MigrationHelper - Data Migration from Old System
 * Aegean Dominance - İzmir Tenteci V2
 */

declare(strict_types=1);

class MigrationHelper
{
    private PDO $oldDb;
    private Database $newDb;
    private array $log = [];

    public function __construct()
    {
        $this->newDb = Database::getInstance();
        $this->connectOldDatabase();
    }

    /**
     * Connect to old database
     */
    private function connectOldDatabase(): void
    {
        try {
            $dsn = 'mysql:host=localhost;dbname=izmirtenteci_tente;charset=utf8mb4';
            $this->oldDb = new PDO($dsn, 'root', '', [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]);
            $this->log[] = "✅ Eski veritabanına bağlanıldı";
        } catch (PDOException $e) {
            $this->log[] = "❌ Eski veritabanı bağlantı hatası: " . $e->getMessage();
            throw $e;
        }
    }

    /**
     * Run full migration
     */
    public function run(): array
    {
        $this->log[] = "🚀 Migrasyon başlatılıyor...";
        
        try {
            $this->migrateSettings();
            $this->migrateTestimonials();
            $this->migrateBlogPosts();
            $this->log[] = "✅ Migrasyon tamamlandı!";
        } catch (Exception $e) {
            $this->log[] = "❌ Migrasyon hatası: " . $e->getMessage();
        }

        return $this->log;
    }

    /**
     * Migrate settings from old database
     */
    public function migrateSettings(): void
    {
        $this->log[] = "📦 Settings migrasyonu başlıyor...";

        $oldSettings = $this->oldDb->query(
            "SELECT setting_key, setting_value, setting_type, category, description 
             FROM settings WHERE is_active = 1"
        )->fetchAll();

        $count = 0;
        foreach ($oldSettings as $setting) {
            $sql = "INSERT INTO settings (setting_key, setting_value, setting_type, category, description)
                    VALUES (?, ?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)";
            
            $this->newDb->execute($sql, [
                $setting['setting_key'],
                $setting['setting_value'],
                $setting['setting_type'],
                $setting['category'],
                $setting['description']
            ]);
            $count++;
        }

        $this->log[] = "✅ {$count} ayar migrate edildi";
    }

    /**
     * Migrate blog posts
     */
    public function migrateBlogPosts(): void
    {
        $this->log[] = "📦 Blog posts migrasyonu başlıyor...";

        $oldPosts = $this->oldDb->query(
            "SELECT title, slug, content, excerpt, author, category, tags, 
                    featured_image, status, seo_title, seo_description, views, created_at
             FROM blog_posts WHERE status = 'published'"
        )->fetchAll();

        $count = 0;
        foreach ($oldPosts as $post) {
            $sql = "INSERT INTO blog_posts 
                    (title, slug, content, excerpt, author, category, tags, 
                     featured_image, status, meta_title, meta_description, view_count, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'published', ?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE content = VALUES(content)";
            
            $this->newDb->execute($sql, [
                $post['title'],
                $post['slug'],
                $post['content'],
                $post['excerpt'],
                $post['author'],
                $post['category'],
                $post['tags'],
                $post['featured_image'],
                $post['seo_title'],
                $post['seo_description'],
                $post['views'],
                $post['created_at']
            ]);
            $count++;
        }

        $this->log[] = "✅ {$count} blog yazısı migrate edildi";
    }

    /**
     * Migrate testimonials (create from sample data if not exists)
     */
    public function migrateTestimonials(): void
    {
        $this->log[] = "📦 Testimonials kontrol ediliyor...";

        // Check if testimonials already exist
        $count = $this->newDb->fetchColumn("SELECT COUNT(*) FROM testimonials");
        
        if ($count > 0) {
            $this->log[] = "ℹ️ Testimonials zaten mevcut ({$count} adet)";
            return;
        }

        $this->log[] = "✅ Varsayılan testimonials zaten schema.sql'de eklendi";
    }

    /**
     * Extract service content from old PHP files
     */
    public function extractServiceContent(string $slug): ?array
    {
        $fileMap = [
            'bioklimatik-pergola' => 'bioklimatik-pergola.php',
            'pergola-tente' => 'pergola-tente-urunleri.php',
            'askili-pergola' => 'askili-pergola.php',
            'mafsalli-tente' => 'mafsalli-tente-urunleri.php',
            'kasetli-tente' => 'kasetli-tente-urunleri.php',
            'zip-perde' => 'zip-perde-urunleri.php',
            'cam-tavan-sistemleri' => 'cam-tavan-sistemleri.php',
            'giyotin-cam-sistemleri' => 'giyotin-cam-sistemleri.php',
            'surgulu-cam-balkon' => 'surgulu-cam-urunleri.php',
            'wintent-tente' => 'wintent-tente-urunleri.php',
            'radyal-pergola' => 'radyal-pergola-urunleri.php',
            'cift-acilir-pergola' => 'cift-acilir-pergola-sistemleri.php',
            'bombeli-askili-pergola' => 'bombeli-askili.php',
            'cift-acilir-askili' => 'cift-acilir-askili-pergola-sistemleri.php',
            'radyal-cift-acilir' => 'radyal-cift-acilir-urunleri.php',
            'tavan-zip-perde' => 'tavan-zipi-urunleri.php',
            'karpuz-tente' => 'karpuz-ve-tente-urunleri.php'
        ];

        $filename = $fileMap[$slug] ?? null;
        if (!$filename) {
            return null;
        }

        $filepath = 'f:/laragon/www/admin/' . $filename;
        if (!file_exists($filepath)) {
            return null;
        }

        $content = file_get_contents($filepath);
        
        // Extract meta description
        preg_match('/<meta name="description" content="([^"]+)"/', $content, $metaMatch);
        
        // Extract H1 or main title
        preg_match('/<h1[^>]*>([^<]+)<\/h1>/', $content, $h1Match);
        
        // Extract first paragraph
        preg_match('/<p[^>]*>([^<]{50,500})<\/p>/s', $content, $pMatch);

        return [
            'meta_description' => $metaMatch[1] ?? null,
            'title' => $h1Match[1] ?? null,
            'description' => $pMatch[1] ?? null
        ];
    }

    /**
     * Update services with extracted content
     */
    public function enrichServices(): void
    {
        $this->log[] = "📦 Service içerikleri zenginleştiriliyor...";

        $services = $this->newDb->fetchAll("SELECT id, slug FROM services");
        $count = 0;

        foreach ($services as $service) {
            $content = $this->extractServiceContent($service['slug']);
            
            if ($content && ($content['description'] || $content['meta_description'])) {
                $sql = "UPDATE services SET 
                        description = COALESCE(?, description),
                        meta_description = COALESCE(?, meta_description)
                        WHERE id = ?";
                
                $this->newDb->execute($sql, [
                    $content['description'],
                    $content['meta_description'],
                    $service['id']
                ]);
                $count++;
            }
        }

        $this->log[] = "✅ {$count} servis içeriği zenginleştirildi";
    }

    /**
     * Get migration log
     */
    public function getLog(): array
    {
        return $this->log;
    }
}
