<?php
/**
 * iMersRELAY - Super Auto Migrator (UTUH & SIAP PAKAI)
 * Menembak Web App Google Apps Script lu, membaca SEMUA TAB sekaligus,
 * lalu otomatis membuat tabel & memindahkan isinya ke MySQL cPanel.
 */

header("Content-Type: text/html; charset=UTF-8");

// ========================================================
// 1. DATA REAL KONFIGURASI MILIK LU (SUDAH DIKUNCI AMAN)
// ========================================================
$db_host = 'localhost';
$db_name = 'terrykatar_imersrelaydemo'; 
$db_user = 'terrykatar_imersrelaydemo'; 
$db_pass = 'Cj-Kbs0!-Fk#B+VP'; 

// URL Deploy Web App Apps Script lu yang terakhir
$apps_script_url = 'https://script.google.com/macros/s/AKfycbxvNE-egrq1utNnYynPgI5pjK-h3sYTSIaU3VySIRyk8g9i_jOjn8GHDC1s80uZeFWVaQ/exec';

// Pemicu awal data menggunakan ID 'admin'
$admin_id = 'ADM-F509CCDE'; 

// ========================================================
// 2. KONEKSI KE DATABASE MYSQL CPANEL
// ========================================================
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "✅ Koneksi ke MySQL cPanel Berhasil!<br><hr>";
} catch (PDOException $e) {
    die("❌ Koneksi MySQL Gagal: " . $e->getMessage());
}

// ========================================================
// 3. TEMBAK API GOOGLE APPS SCRIPT (TARIK DATA SEMUA TAB)
// ========================================================
echo "🔄 Sedang menarik data dari Google Sheets (Semua Tab)...<br>";

$postPayload = json_encode([
    "action" => "getDashboardData",
    "payload" => ["userId" => $admin_id]
]);

$ch = curl_init($apps_script_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Wajib TRUE agar Google Apps Script redirect URL
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$response = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

if ($curl_error) {
    die("❌ Gagal menembak Google Apps Script: " . $curl_error);
}

$result = json_decode($response, true);

if (!$result || $result['success'] !== true) {
    die("❌ Gagal mengambil data. Pastikan URL Script bener. Response: " . $response);
}

// Data raksasa dari Google Sheets berhasil ditangkap!
$allData = $result['data'];

// Pemetaan nama tabel dan data yang ditarik dari getDashboardData
$tablesToMigrate = [
    'users'     => $allData['allUsers'] ?? [], 
    'products'  => $allData['products'] ?? [],
    'orders'    => $allData['orders'] ?? [],
    'App_menu'  => $allData['dynamicMenus'] ?? [],
    'settings'  => isset($allData['settings']) ? [$allData['settings']] : [] 
];

// Tabel access dibuat strukturnya agar siap dipakai sistem PHP
$tablesToMigrate['access'] = []; 

// ========================================================
// 4. OTOMATISASI PEMBUATAN TABEL & INJEKSI DATA KE MYSQL
// ========================================================
foreach ($tablesToMigrate as $tableName => $rows) {
    echo "📂 Memproses Tabel: <strong>$tableName</strong>...<br>";
    
    // Header cadangan jika data sheet masih kosong melompong
    if (empty($rows)) {
        $defaultHeaders = [
            'users'    => ['id', 'name', 'email', 'phone', 'role', 'created_by', 'password', 'bank_name', 'bank_account', 'bank_owner', 'qris_url', 'plain_password', 'agency_logo_url'],
            'products' => ['id', 'name', 'price', 'imageUrl', 'salespageUrl', 'accessContent'],
            'access'   => ['user_id', 'product_id', 'timestamp'],
            'settings' => ['admin_id', 'brandName', 'logoUrl', 'waProvider', 'waToken', 'waAdmin', 'appUrl', 'emailHeaderBg', 'emailTplAgency', 'emailTplProduct', 'emailTplReset', 'emailTplOrderPending', 'emailTplOrderSuccess', 'emailTplNotifyAgency', 'enableAutoEmail', 'enableAutoWa'],
            'App_menu' => ['id', 'menu_name', 'html_content', 'icon'],
            'orders'   => ['id', 'timestamp', 'product_id', 'product_name', 'price', 'customer_name', 'customer_wa', 'customer_email', 'agency_id', 'status']
        ];
        $headers = $defaultHeaders[$tableName];
    } else {
        // Ambil nama kolom otomatis dari key data Google Sheets lu
        $headers = array_keys($rows[0]);
    }
    
    // Reset ulang tabel lama biar bersih
    $pdo->exec("DROP TABLE IF EXISTS `$tableName`;");
    
    // Bikin kolom di MySQL dengan tipe TEXT dulu semua biar aman nampung data tanpa error tipe data
    $columnDefs = array_map(function($header) {
        return "`$header` TEXT NULL";
    }, $headers);
    
    $createTableSql = "CREATE TABLE `$tableName` (" . implode(', ', $columnDefs) . ") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
    $pdo->exec($createTableSql);
    echo "  -> 🛠️ Tabel `$tableName` berhasil dibuat otomatis di MySQL!<br>";
    
    // Masukkan isi data lamanya
    if (!empty($rows)) {
        $insertedCount = 0;
        $placeholders = implode(', ', array_fill(0, count($headers), '?'));
        $insertSql = "INSERT INTO `$tableName` (`" . implode("`, `", $headers) . "`) VALUES ($placeholders)";
        $stmt = $pdo->prepare($insertSql);
        
        foreach ($rows as $rowObj) {
            $rowData = [];
            foreach ($headers as $head) {
                $val = $rowObj[$head] ?? '';
                $rowData[] = is_array($val) ? json_encode($val) : $val;
            }
            $stmt->execute($rowData);
            $insertedCount++;
        }
        echo "  -> 📝 Berhasil memindahkan <strong>$insertedCount</strong> baris data lama!<br>";
    }
    echo "<br>";
}

echo "<hr>🏆 <strong>MIGRASI TOTAL SELESAI!</strong> Silakan buka phpMyAdmin di cPanel lu, 6 tabel sudah terbuat otomatis beserta isinya.";