<?php
/**
 * GlowSpace JSON to MySQL Migration Script
 * This script migrates all existing JSON data to MySQL database
 * with backup and rollback support.
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

define('GS_ROOT', __DIR__ . '/..');
define('GS_DATA', GS_ROOT . '/data');
define('GS_BACKUP', GS_ROOT . '/data/backup_' . date('Y-m-d_H-i-s'));

// Database configuration - UPDATE THESE VALUES
define('DB_HOST', 'localhost');
define('DB_NAME', 'jisanpro2_glowspace');
define('DB_USER', 'jisanpro2_glowadmin');
define('DB_PASS', 'GloW@2026#Space');

class GlowSpaceMigrator {
    private $pdo;
    private $logs = [];
    private $backupDir;
    private $stats = [
        'products' => 0,
        'categories' => 0,
        'orders' => 0,
        'customers' => 0,
        'landing_pages' => 0,
        'banners' => 0,
        'coupons' => 0,
        'reviews' => 0,
        'admins' => 0,
        'settings' => 0,
        'total' => 0
    ];

    public function __construct() {
        $this->backupDir = GS_BACKUP;
        $this->connectDatabase();
    }

    private function connectDatabase() {
        try {
            $this->pdo = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
            $this->log('Database connected successfully');
        } catch (PDOException $e) {
            $this->log('Database connection failed: ' . $e->getMessage(), 'error');
            die('Database connection failed. Please check your database configuration.');
        }
    }

    private function log($message, $type = 'info') {
        $timestamp = date('Y-m-d H:i:s');
        $this->logs[] = "[$timestamp] [$type] $message";
        echo "[$timestamp] [$type] $message\n";
    }

    private function readJson($file) {
        $path = GS_DATA . '/' . $file . '.json';
        if (!file_exists($path)) {
            $this->log("File not found: $file", 'warning');
            return [];
        }
        $content = file_get_contents($path);
        $data = json_decode($content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->log("JSON decode error in $file: " . json_last_error_msg(), 'error');
            return [];
        }
        return is_array($data) ? $data : [];
    }

    private function createBackup() {
        $this->log('Creating backup of JSON files...');
        
        if (!file_exists($this->backupDir)) {
            mkdir($this->backupDir, 0755, true);
        }

        $jsonFiles = [
            'products', 'categories', 'orders', 'customers', 
            'landing_pages', 'banners', 'coupons', 'reviews', 
            'admins', 'settings', 'logs'
        ];

        foreach ($jsonFiles as $file) {
            $source = GS_DATA . '/' . $file . '.json';
            if (file_exists($source)) {
                $dest = $this->backupDir . '/' . $file . '.json';
                copy($source, $dest);
                $this->log("Backed up: $file");
            }
        }

        $this->log('Backup created at: ' . $this->backupDir);
        return true;
    }

    private function migrateCategories() {
        $this->log('Migrating categories...');
        $categories = $this->readJson('categories');
        
        $stmt = $this->pdo->prepare("
            INSERT INTO categories (category_id, name, icon, description, status, created_at, updated_at)
            VALUES (:category_id, :name, :icon, :description, :status, :created_at, :updated_at)
            ON DUPLICATE KEY UPDATE name = VALUES(name), icon = VALUES(icon), status = VALUES(status)
        ");

        foreach ($categories as $cat) {
            try {
                $stmt->execute([
                    ':category_id' => $cat['id'] ?? '',
                    ':name' => $cat['name'] ?? '',
                    ':icon' => $cat['icon'] ?? '',
                    ':description' => $cat['description'] ?? '',
                    ':status' => $cat['status'] ?? 1,
                    ':created_at' => date('Y-m-d H:i:s'),
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);
                $this->stats['categories']++;
            } catch (PDOException $e) {
                $this->log("Error migrating category {$cat['id']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['categories']} categories");
    }

    private function migrateProducts() {
        $this->log('Migrating products...');
        $products = $this->readJson('products');
        
        $productStmt = $this->pdo->prepare("
            INSERT INTO products (
                product_id, title, subtitle, slug, brand, category_id, sub_category,
                description, features, specifications, price, offer_price, discount,
                stock, warranty, color, sizes, size_unit, featured, trending,
                best_seller, flash_sale, new_arrival, recommended, status,
                views, rating, created_at, updated_at
            ) VALUES (
                :product_id, :title, :subtitle, :slug, :brand, :category_id, :sub_category,
                :description, :features, :specifications, :price, :offer_price, :discount,
                :stock, :warranty, :color, :sizes, :size_unit, :featured, :trending,
                :best_seller, :flash_sale, :new_arrival, :recommended, :status,
                :views, :rating, :created_at, :updated_at
            ) ON DUPLICATE KEY UPDATE 
                title = VALUES(title), price = VALUES(price), offer_price = VALUES(offer_price),
                stock = VALUES(stock), status = VALUES(status), updated_at = VALUES(updated_at)
        ");

        $imageStmt = $this->pdo->prepare("
            INSERT INTO product_images (product_id, image_path, image_order, created_at)
            VALUES (:product_id, :image_path, :image_order, :created_at)
        ");

        foreach ($products as $prod) {
            try {
                // Decode HTML entities in text fields
                $title = $this->decodeHtmlEntities($prod['title'] ?? '');
                $subtitle = $this->decodeHtmlEntities($prod['subtitle'] ?? '');
                $description = $this->decodeHtmlEntities($prod['description'] ?? '');
                $features = $this->decodeHtmlEntities($prod['features'] ?? '');
                $sizes = $this->decodeHtmlEntities($prod['sizes'] ?? '');

                // Handle specifications
                $specifications = null;
                if (!empty($prod['specifications']) && is_array($prod['specifications'])) {
                    $specifications = json_encode($prod['specifications']);
                }

                $productStmt->execute([
                    ':product_id' => $prod['id'] ?? '',
                    ':title' => $title,
                    ':subtitle' => $subtitle,
                    ':slug' => $prod['slug'] ?? '',
                    ':brand' => $prod['brand'] ?? '',
                    ':category_id' => $prod['category'] ?? '',
                    ':sub_category' => $prod['sub_category'] ?? '',
                    ':description' => $description,
                    ':features' => $features,
                    ':specifications' => $specifications,
                    ':price' => $prod['price'] ?? 0,
                    ':offer_price' => $prod['offer_price'] ?? 0,
                    ':discount' => $prod['discount'] ?? 0,
                    ':stock' => $prod['stock'] ?? 0,
                    ':warranty' => $prod['warranty'] ?? '',
                    ':color' => $prod['color'] ?? '',
                    ':sizes' => $sizes,
                    ':size_unit' => $prod['size_unit'] ?? '',
                    ':featured' => (bool)($prod['featured'] ?? false),
                    ':trending' => (bool)($prod['trending'] ?? false),
                    ':best_seller' => (bool)($prod['best_seller'] ?? false),
                    ':flash_sale' => (bool)($prod['flash_sale'] ?? false),
                    ':new_arrival' => (bool)($prod['new_arrival'] ?? false),
                    ':recommended' => (bool)($prod['recommended'] ?? false),
                    ':status' => (int)($prod['status'] ?? 1),
                    ':views' => $prod['views'] ?? 0,
                    ':rating' => $prod['rating'] ?? 0,
                    ':created_at' => $prod['created'] ?? date('Y-m-d H:i:s'),
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);

                // Migrate product images
                if (!empty($prod['images']) && is_array($prod['images'])) {
                    foreach ($prod['images'] as $index => $image) {
                        $imageStmt->execute([
                            ':product_id' => $prod['id'] ?? '',
                            ':image_path' => $image,
                            ':image_order' => $index,
                            ':created_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                }

                $this->stats['products']++;
            } catch (PDOException $e) {
                $this->log("Error migrating product {$prod['id']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['products']} products");
    }

    private function migrateOrders() {
        $this->log('Migrating orders...');
        $orders = $this->readJson('orders');
        
        $orderStmt = $this->pdo->prepare("
            INSERT INTO orders (
                order_id, customer_name, customer_phone, customer_alt_phone,
                customer_email, customer_district, customer_upazila,
                customer_address, customer_postal, subtotal, discount,
                shipping, total, coupon_code, status, payment_status,
                payment_method, tracking_number, created_at, updated_at
            ) VALUES (
                :order_id, :customer_name, :customer_phone, :customer_alt_phone,
                :customer_email, :customer_district, :customer_upazila,
                :customer_address, :customer_postal, :subtotal, :discount,
                :shipping, :total, :coupon_code, :status, :payment_status,
                :payment_method, :tracking_number, :created_at, :updated_at
            ) ON DUPLICATE KEY UPDATE 
                status = VALUES(status), tracking_number = VALUES(tracking_number), updated_at = VALUES(updated_at)
        ");

        $itemStmt = $this->pdo->prepare("
            INSERT INTO order_items (
                order_id, product_id, product_title, product_image,
                price, original_price, size, quantity, subtotal, created_at
            ) VALUES (
                :order_id, :product_id, :product_title, :product_image,
                :price, :original_price, :size, :quantity, :subtotal, :created_at
            )
        ");

        foreach ($orders as $order) {
            try {
                $customer = $order['customer'] ?? [];
                $orderStmt->execute([
                    ':order_id' => $order['id'] ?? '',
                    ':customer_name' => $customer['name'] ?? '',
                    ':customer_phone' => $customer['phone'] ?? '',
                    ':customer_alt_phone' => $customer['alt_phone'] ?? '',
                    ':customer_email' => $customer['email'] ?? '',
                    ':customer_district' => $customer['district'] ?? '',
                    ':customer_upazila' => $customer['upazila'] ?? '',
                    ':customer_address' => $customer['address'] ?? '',
                    ':customer_postal' => $customer['postal'] ?? '',
                    ':subtotal' => $order['subtotal'] ?? 0,
                    ':discount' => $order['discount'] ?? 0,
                    ':shipping' => $order['shipping'] ?? 0,
                    ':total' => $order['total'] ?? 0,
                    ':coupon_code' => $order['coupon'] ?? '',
                    ':status' => $order['status'] ?? 'pending',
                    ':payment_status' => 'pending',
                    ':payment_method' => 'cod',
                    ':tracking_number' => $order['tracking'] ?? '',
                    ':created_at' => $order['date'] ?? date('Y-m-d H:i:s'),
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);

                // Migrate order items
                if (!empty($order['items']) && is_array($order['items'])) {
                    foreach ($order['items'] as $item) {
                        $itemStmt->execute([
                            ':order_id' => $order['id'] ?? '',
                            ':product_id' => $item['id'] ?? '',
                            ':product_title' => $item['title'] ?? '',
                            ':product_image' => $item['image'] ?? '',
                            ':price' => $item['price'] ?? 0,
                            ':original_price' => $item['original_price'] ?? 0,
                            ':size' => $item['size'] ?? '',
                            ':quantity' => $item['qty'] ?? 1,
                            ':subtotal' => ($item['price'] ?? 0) * ($item['qty'] ?? 1),
                            ':created_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                }

                $this->stats['orders']++;
            } catch (PDOException $e) {
                $this->log("Error migrating order {$order['id']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['orders']} orders");
    }

    private function migrateCustomers() {
        $this->log('Migrating customers...');
        $customers = $this->readJson('customers');
        
        // Customers will be stored as addresses for now, user accounts can be created later
        $this->log("Found {$this->stats['customers']} customer records (will be available as order history)");
    }

    private function migrateLandingPages() {
        $this->log('Migrating landing pages...');
        $landingPages = $this->readJson('landing_pages');
        
        $stmt = $this->pdo->prepare("
            INSERT INTO landing_pages (
                product_id, slug, enabled, headline, description, banner_image,
                promo_video_url, countdown_enabled, countdown_end, benefits,
                before_image, after_image, testimonials, feature_icons, faq,
                cta_text, delivery_info, return_policy, fb_pixel, tiktok_pixel,
                ga_id, meta_tags, seo_title, seo_description, seo_keywords,
                og_image, canonical_url, views, clicks, add_to_cart, orders,
                created_at, updated_at
            ) VALUES (
                :product_id, :slug, :enabled, :headline, :description, :banner_image,
                :promo_video_url, :countdown_enabled, :countdown_end, :benefits,
                :before_image, :after_image, :testimonials, :feature_icons, :faq,
                :cta_text, :delivery_info, :return_policy, :fb_pixel, :tiktok_pixel,
                :ga_id, :meta_tags, :seo_title, :seo_description, :seo_keywords,
                :og_image, :canonical_url, :views, :clicks, :add_to_cart, :orders,
                :created_at, :updated_at
            ) ON DUPLICATE KEY UPDATE 
                enabled = VALUES(enabled), headline = VALUES(headline), updated_at = VALUES(updated_at)
        ");

        foreach ($landingPages as $lp) {
            try {
                $headline = $this->decodeHtmlEntities($lp['headline'] ?? '');
                $description = $this->decodeHtmlEntities($lp['description'] ?? '');
                $cta_text = $this->decodeHtmlEntities($lp['cta_text'] ?? '');
                $delivery_info = $this->decodeHtmlEntities($lp['delivery_info'] ?? '');
                $return_policy = $this->decodeHtmlEntities($lp['return_policy'] ?? '');
                $seo_title = $this->decodeHtmlEntities($lp['seo_title'] ?? '');
                $seo_description = $this->decodeHtmlEntities($lp['seo_description'] ?? '');

                $countdownEnd = null;
                if (!empty($lp['countdown_end'])) {
                    $countdownEnd = date('Y-m-d H:i:s', strtotime($lp['countdown_end']));
                }

                $stmt->execute([
                    ':product_id' => $lp['product_id'] ?? '',
                    ':slug' => $lp['slug'] ?? '',
                    ':enabled' => (bool)($lp['enabled'] ?? true),
                    ':headline' => $headline,
                    ':description' => $description,
                    ':banner_image' => $lp['banner_image'] ?? '',
                    ':promo_video_url' => $lp['promo_video_url'] ?? '',
                    ':countdown_enabled' => (bool)($lp['countdown_enabled'] ?? false),
                    ':countdown_end' => $countdownEnd,
                    ':benefits' => !empty($lp['benefits']) ? json_encode($lp['benefits']) : null,
                    ':before_image' => $lp['before_image'] ?? '',
                    ':after_image' => $lp['after_image'] ?? '',
                    ':testimonials' => !empty($lp['testimonials']) ? json_encode($lp['testimonials']) : null,
                    ':feature_icons' => !empty($lp['feature_icons']) ? json_encode($lp['feature_icons']) : null,
                    ':faq' => !empty($lp['faq']) ? json_encode($lp['faq']) : null,
                    ':cta_text' => $cta_text,
                    ':delivery_info' => $delivery_info,
                    ':return_policy' => $return_policy,
                    ':fb_pixel' => $lp['fb_pixel'] ?? '',
                    ':tiktok_pixel' => $lp['tiktok_pixel'] ?? '',
                    ':ga_id' => $lp['ga_id'] ?? '',
                    ':meta_tags' => $lp['meta_tags'] ?? '',
                    ':seo_title' => $seo_title,
                    ':seo_description' => $seo_description,
                    ':seo_keywords' => $lp['seo_keywords'] ?? '',
                    ':og_image' => $lp['og_image'] ?? '',
                    ':canonical_url' => $lp['canonical_url'] ?? '',
                    ':views' => $lp['views'] ?? 0,
                    ':clicks' => $lp['clicks'] ?? 0,
                    ':add_to_cart' => $lp['add_to_cart'] ?? 0,
                    ':orders' => $lp['orders'] ?? 0,
                    ':created_at' => $lp['created'] ?? date('Y-m-d H:i:s'),
                    ':updated_at' => $lp['updated'] ?? date('Y-m-d H:i:s')
                ]);

                $this->stats['landing_pages']++;
            } catch (PDOException $e) {
                $this->log("Error migrating landing page {$lp['slug']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['landing_pages']} landing pages");
    }

    private function migrateBanners() {
        $this->log('Migrating banners...');
        $banners = $this->readJson('banners');
        
        $stmt = $this->pdo->prepare("
            INSERT INTO banners (
                banner_id, title, subtitle, image, link, position,
                display_order, status, created_at, updated_at
            ) VALUES (
                :banner_id, :title, :subtitle, :image, :link, :position,
                :display_order, :status, :created_at, :updated_at
            ) ON DUPLICATE KEY UPDATE 
                title = VALUES(title), image = VALUES(image), status = VALUES(status)
        ");

        foreach ($banners as $banner) {
            try {
                $stmt->execute([
                    ':banner_id' => $banner['id'] ?? '',
                    ':title' => $banner['title'] ?? '',
                    ':subtitle' => $banner['subtitle'] ?? '',
                    ':image' => $banner['image'] ?? '',
                    ':link' => $banner['link'] ?? '',
                    ':position' => 'home',
                    ':display_order' => 0,
                    ':status' => $banner['status'] ?? 1,
                    ':created_at' => date('Y-m-d H:i:s'),
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);

                $this->stats['banners']++;
            } catch (PDOException $e) {
                $this->log("Error migrating banner {$banner['id']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['banners']} banners");
    }

    private function migrateCoupons() {
        $this->log('Migrating coupons...');
        $coupons = $this->readJson('coupons');
        
        $stmt = $this->pdo->prepare("
            INSERT INTO coupons (
                coupon_id, code, discount, discount_type, min_purchase,
                usage_limit, used_count, expiry_date, status, created_at, updated_at
            ) VALUES (
                :coupon_id, :code, :discount, :discount_type, :min_purchase,
                :usage_limit, :used_count, :expiry_date, :status, :created_at, :updated_at
            ) ON DUPLICATE KEY UPDATE 
                discount = VALUES(discount), status = VALUES(status)
        ");

        foreach ($coupons as $coupon) {
            try {
                $expiryDate = null;
                if (!empty($coupon['expiry'])) {
                    $expiryDate = date('Y-m-d H:i:s', strtotime($coupon['expiry']));
                }

                $stmt->execute([
                    ':coupon_id' => $coupon['id'] ?? '',
                    ':code' => $coupon['code'] ?? '',
                    ':discount' => $coupon['discount'] ?? 0,
                    ':discount_type' => $coupon['type'] ?? 'percent',
                    ':min_purchase' => $coupon['min_purchase'] ?? 0,
                    ':usage_limit' => $coupon['usage_limit'] ?? null,
                    ':used_count' => $coupon['used_count'] ?? 0,
                    ':expiry_date' => $expiryDate,
                    ':status' => $coupon['status'] ?? 1,
                    ':created_at' => date('Y-m-d H:i:s'),
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);

                $this->stats['coupons']++;
            } catch (PDOException $e) {
                $this->log("Error migrating coupon {$coupon['id']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['coupons']} coupons");
    }

    private function migrateReviews() {
        $this->log('Migrating reviews...');
        $reviews = $this->readJson('reviews');
        
        $stmt = $this->pdo->prepare("
            INSERT INTO reviews (
                review_id, product_id, name, rating, text, status, created_at, updated_at
            ) VALUES (
                :review_id, :product_id, :name, :rating, :text, :status, :created_at, :updated_at
            ) ON DUPLICATE KEY UPDATE 
                rating = VALUES(rating), text = VALUES(text), status = VALUES(status)
        ");

        foreach ($reviews as $review) {
            try {
                $text = $this->decodeHtmlEntities($review['text'] ?? '');

                $stmt->execute([
                    ':review_id' => $review['id'] ?? '',
                    ':product_id' => $review['product_id'] ?? '',
                    ':name' => $review['name'] ?? '',
                    ':rating' => $review['rating'] ?? 5,
                    ':text' => $text,
                    ':status' => $review['status'] ?? 0,
                    ':created_at' => $review['date'] ?? date('Y-m-d H:i:s'),
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);

                $this->stats['reviews']++;
            } catch (PDOException $e) {
                $this->log("Error migrating review {$review['id']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['reviews']} reviews");
    }

    private function migrateAdmins() {
        $this->log('Migrating admins...');
        $admins = $this->readJson('admins');
        
        $stmt = $this->pdo->prepare("
            INSERT INTO admin_users (
                admin_id, username, password, email, full_name, role, status, created_at, updated_at
            ) VALUES (
                :admin_id, :username, :password, :email, :full_name, :role, :status, :created_at, :updated_at
            ) ON DUPLICATE KEY UPDATE 
                password = VALUES(password), status = VALUES(status)
        ");

        foreach ($admins as $admin) {
            try {
                $stmt->execute([
                    ':admin_id' => $admin['id'] ?? '',
                    ':username' => $admin['username'] ?? '',
                    ':password' => $admin['password'] ?? '',
                    ':email' => $admin['email'] ?? '',
                    ':full_name' => $admin['full_name'] ?? $admin['username'],
                    ':role' => $admin['role'] ?? 'admin',
                    ':status' => 'active',
                    ':created_at' => date('Y-m-d H:i:s'),
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);

                $this->stats['admins']++;
            } catch (PDOException $e) {
                $this->log("Error migrating admin {$admin['id']}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['admins']} admins");
    }

    private function migrateSettings() {
        $this->log('Migrating settings...');
        $settings = $this->readJson('settings');
        
        if (empty($settings)) {
            $this->log('Settings file is empty, using default settings from schema');
            return;
        }

        $stmt = $this->pdo->prepare("
            INSERT INTO settings (setting_key, setting_value, setting_type, category, updated_at)
            VALUES (:setting_key, :setting_value, :setting_type, :category, :updated_at)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = VALUES(updated_at)
        ");

        foreach ($settings as $key => $value) {
            try {
                $settingType = 'string';
                if (is_bool($value)) {
                    $settingType = 'boolean';
                    $value = $value ? 'true' : 'false';
                } elseif (is_numeric($value)) {
                    $settingType = 'number';
                } elseif (is_array($value)) {
                    $settingType = 'json';
                    $value = json_encode($value);
                }

                $stmt->execute([
                    ':setting_key' => $key,
                    ':setting_value' => $value,
                    ':setting_type' => $settingType,
                    ':category' => 'general',
                    ':updated_at' => date('Y-m-d H:i:s')
                ]);

                $this->stats['settings']++;
            } catch (PDOException $e) {
                $this->log("Error migrating setting {$key}: " . $e->getMessage(), 'error');
            }
        }

        $this->log("Migrated {$this->stats['settings']} settings");
    }

    private function decodeHtmlEntities($text) {
        if (empty($text)) return '';
        // Decode HTML entities like &amp;quot; to "
        return html_entity_decode((string)$text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    }

    private function verifyMigration() {
        $this->log('Verifying migration...');
        
        $tables = [
            'products' => 'products',
            'categories' => 'categories',
            'orders' => 'orders',
            'landing_pages' => 'landing_pages',
            'banners' => 'banners',
            'coupons' => 'coupons',
            'reviews' => 'reviews',
            'admin_users' => 'admins'
        ];

        foreach ($tables as $table => $statKey) {
            $stmt = $this->pdo->query("SELECT COUNT(*) FROM $table");
            $count = $stmt->fetchColumn();
            $this->log("$table: $count records");
        }

        $this->stats['total'] = array_sum($this->stats);
        $this->log("Total migrated records: {$this->stats['total']}");
    }

    private function saveLogs() {
        $logFile = $this->backupDir . '/migration_log.txt';
        file_put_contents($logFile, implode("\n", $this->logs));
        $this->log("Migration log saved to: $logFile");
    }

    public function run() {
        echo "\n";
        echo "========================================\n";
        echo "  GlowSpace JSON to MySQL Migration\n";
        echo "========================================\n\n";

        // Step 1: Create backup
        $this->createBackup();

        // Step 2: Migrate data
        $this->migrateCategories();
        $this->migrateProducts();
        $this->migrateOrders();
        $this->migrateCustomers();
        $this->migrateLandingPages();
        $this->migrateBanners();
        $this->migrateCoupons();
        $this->migrateReviews();
        $this->migrateAdmins();
        $this->migrateSettings();

        // Step 3: Verify migration
        $this->verifyMigration();

        // Step 4: Save logs
        $this->saveLogs();

        echo "\n";
        echo "========================================\n";
        echo "  Migration Completed Successfully!\n";
        echo "========================================\n";
        echo "\nStatistics:\n";
        foreach ($this->stats as $key => $value) {
            echo "  $key: $value\n";
        }
        echo "\nBackup location: {$this->backupDir}\n";
        echo "\nNext steps:\n";
        echo "1. Update your database configuration in config.php\n";
        echo "2. Test the website to ensure everything works\n";
        echo "3. If there are any issues, you can restore from the backup\n";
        echo "\n";
    }
}

// Run migration
if (php_sapi_name() === 'cli') {
    $migrator = new GlowSpaceMigrator();
    $migrator->run();
} else {
    echo "This script must be run from command line: php migrate.php\n";
}
