<?php
// ==========================================================
// IMPORT DATABASE BIOWIN - STREAMING / AUTO-RESUME IMPORTER
// Upload ke: public_html/importbio8291/import-biowin.php
// Upload SQL ke folder yang sama: u1734119_biowin.sql
//
// PENTING: HAPUS FOLDER importbio8291 SETELAH IMPORT SELESAI.
// ==========================================================

ini_set('display_errors', 1);
ini_set('memory_limit', '1024M');
ini_set('max_execution_time', 0);
set_time_limit(0);

// ===============================
// KONFIGURASI DATABASE BIOWIN
// ===============================
$db_host = 'localhost';
$db_name = 'lucyandr_biowinnew';
$db_user = 'lucyandr_biowin';
$db_pass = 'lucyandri123';
$sql_file = __DIR__ . '/u1734119_biowin.sql';

// File progress otomatis, jangan diubah
$progress_file = __DIR__ . '/import-biowin-progress.json';

// Durasi kerja per refresh browser, dibuat aman untuk shared hosting
$max_seconds_per_run = 20;

// ===============================
// JANGAN EDIT DI BAWAH INI
// ===============================

header('Content-Type: text/html; charset=utf-8');
echo "<pre>";
echo "=== IMPORT DATABASE BIOWIN ===\n\n";

if (!file_exists($sql_file)) {
    die("GAGAL: File SQL tidak ditemukan.\n\nHarus ada di:\n" . $sql_file . "\n\nPastikan nama file SQL persis: u1734119_biowin.sql");
}

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

if ($mysqli->connect_error) {
    die("GAGAL KONEKSI DATABASE:\n" . $mysqli->connect_error . "\n\nCek:\n1. Database lucyandr_biowinnew sudah dibuat\n2. User lucyandr_biowin sudah Add ke database\n3. ALL PRIVILEGES sudah dicentang\n4. Password database benar\n");
}

$mysqli->set_charset("utf8mb4");
$mysqli->query("SET FOREIGN_KEY_CHECKS=0");
$mysqli->query("SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");

$file_size = filesize($sql_file);
$start_time = time();

$progress = [
    'offset' => 0,
    'success' => 0,
    'error' => 0,
    'line' => 0,
    'last_error' => ''
];

if (file_exists($progress_file)) {
    $saved = json_decode(file_get_contents($progress_file), true);
    if (is_array($saved)) {
        $progress = array_merge($progress, $saved);
    }
}

$handle = fopen($sql_file, 'r');
if (!$handle) {
    die("GAGAL: Tidak bisa membuka file SQL.");
}

fseek($handle, (int)$progress['offset']);

$query = '';
$queries_this_run = 0;

echo "Database tujuan : {$db_name}\n";
echo "User database   : {$db_user}\n";
echo "File SQL        : " . basename($sql_file) . "\n";
echo "Ukuran file     : " . round($file_size / 1024 / 1024, 2) . " MB\n";
echo "Mulai dari byte : {$progress['offset']}\n\n";

while (!feof($handle)) {
    $line = fgets($handle);
    if ($line === false) {
        break;
    }

    $progress['line']++;
    $trimmed = trim($line);

    // Skip komentar dan baris kosong saat query belum terbentuk
    if ($query === '' && ($trimmed === '' || strpos($trimmed, '--') === 0 || strpos($trimmed, '#') === 0)) {
        $progress['offset'] = ftell($handle);
        continue;
    }

    // Skip perintah yang biasanya tidak dibutuhkan / bisa error di shared hosting
    if ($query === '' && (
        stripos($trimmed, 'CREATE DATABASE') === 0 ||
        stripos($trimmed, 'USE ') === 0 ||
        stripos($trimmed, 'DELIMITER ') === 0
    )) {
        $progress['offset'] = ftell($handle);
        continue;
    }

    $query .= $line;

    // Query dianggap selesai kalau baris berakhir titik koma
    if (substr(rtrim($line), -1) === ';') {
        if ($mysqli->query($query)) {
            $progress['success']++;
        } else {
            $progress['error']++;
            $progress['last_error'] = "Line sekitar {$progress['line']}: " . $mysqli->error;
            echo "ERROR dilewati: {$progress['last_error']}\n";
        }

        $query = '';
        $queries_this_run++;
        $progress['offset'] = ftell($handle);

        if ($queries_this_run % 50 === 0) {
            $percent = $file_size > 0 ? round(($progress['offset'] / $file_size) * 100, 2) : 0;
            echo "Progress: {$percent}% | Sukses: {$progress['success']} | Error: {$progress['error']}\n";
            @ob_flush();
            flush();
        }

        // Berhenti sebentar lalu auto-refresh supaya tidak timeout
        if ((time() - $start_time) >= $max_seconds_per_run) {
            file_put_contents($progress_file, json_encode($progress));
            $percent = $file_size > 0 ? round(($progress['offset'] / $file_size) * 100, 2) : 0;

            echo "\nBerhenti sementara untuk menghindari timeout.\n";
            echo "Progress sekarang: {$percent}%\n";
            echo "Browser akan lanjut otomatis dalam 2 detik...\n";
            echo '<meta http-equiv="refresh" content="2">';
            echo "</pre>";
            fclose($handle);
            $mysqli->query("SET FOREIGN_KEY_CHECKS=1");
            $mysqli->close();
            exit;
        }
    }
}

fclose($handle);
$mysqli->query("SET FOREIGN_KEY_CHECKS=1");
$mysqli->close();

if ($progress['offset'] >= $file_size || feof($handle)) {
    if (file_exists($progress_file)) {
        unlink($progress_file);
    }

    echo "\n=============================\n";
    echo "IMPORT SELESAI\n";
    echo "Query sukses : {$progress['success']}\n";
    echo "Query error  : {$progress['error']}\n";
    echo "Last error   : {$progress['last_error']}\n";
    echo "=============================\n\n";
    echo "Langkah berikutnya:\n";
    echo "1. Edit wp-config.php Biowin\n";
    echo "2. DB_NAME = lucyandr_biowinnew\n";
    echo "3. DB_USER = lucyandr_biowin\n";
    echo "4. DB_PASSWORD = lucyandri123\n";
    echo "5. table_prefix = wpmh_\n";
    echo "6. HAPUS folder importbio8291 setelah semua normal.\n";
    echo "</pre>";
    exit;
}

file_put_contents($progress_file, json_encode($progress));
echo "\nImport belum selesai. Refresh manual halaman ini kalau tidak lanjut otomatis.\n";
echo '<meta http-equiv="refresh" content="2">';
echo "</pre>";
?>