<?php
/**
 * Test Sync Full Process - dengan data yang dibatasi untuk testing
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(60); // 1 menit untuk testing

echo "<h3>Test Sync Full Process</h3>";

// Cek apakah POST sync diterima
if (isset($_POST['test_sync'])) {
    echo "<div style='color: green; font-weight: bold;'>✅ Form submitted successfully!</div>";
    
    // Konfigurasi
    $sipp_config = [
        'host' => '192.168.1.240',
        'dbname' => 'sippbaco',
        'username' => 'pnwtp',
        'password' => 'pnwtp2019',
        'port' => 3306
    ];
    
    $sqlite_path = 'data/sipp_sync.sqlite';
    
    echo "<h4>Full Sync Test (Limited to 50 records)</h4>";
    
    try {
        // SIPP Connection
        $dsn = "mysql:host={$sipp_config['host']};port={$sipp_config['port']};dbname={$sipp_config['dbname']};charset=utf8mb4";
        $sipp_pdo = new PDO($dsn, $sipp_config['username'], $sipp_config['password']);
        $sipp_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // SQLite Connection
        $sqlite_pdo = new PDO("sqlite:$sqlite_path");
        $sqlite_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Create table
        $sql = "CREATE TABLE IF NOT EXISTS arsip (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            nomor_perkara TEXT NOT NULL,
            nomor_arsip TEXT,
            no_ruang TEXT,
            no_lemari TEXT,
            no_rak TEXT,
            no_berkas TEXT,
            tanggal_sync DATETIME DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(nomor_perkara, nomor_arsip)
        )";
        $sqlite_pdo->exec($sql);
        
        echo "<div style='color: green;'>✅ Connections and table OK</div>";
        
        // Clear old data
        $sqlite_pdo->exec("DELETE FROM arsip");
        echo "<div style='color: orange;'>🗑️ Old data cleared</div>";
        
        // Fetch limited data from SIPP
        $start_time = microtime(true);
        $sql = "SELECT * FROM arsip ORDER BY nomor_perkara LIMIT 50";
        $stmt = $sipp_pdo->prepare($sql);
        $stmt->execute();
        
        $insert_sql = "INSERT OR REPLACE INTO arsip 
                      (nomor_perkara, nomor_arsip, no_ruang, no_lemari, no_rak, no_berkas) 
                      VALUES (?, ?, ?, ?, ?, ?)";
        $insert_stmt = $sqlite_pdo->prepare($insert_sql);
        
        $processed = 0;
        $success = 0;
        $errors = 0;
        
        echo "<div style='background: #f8f9fa; padding: 10px; border: 1px solid #dee2e6; margin: 10px 0;'>";
        echo "<strong>Processing Records:</strong><br>";
        
        $sqlite_pdo->beginTransaction();
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $processed++;
            
            try {
                $insert_stmt->execute([
                    $row['nomor_perkara'] ?? '',
                    $row['nomor_arsip'] ?? '',
                    $row['no_ruang'] ?? '',
                    $row['no_lemari'] ?? '',
                    $row['no_rak'] ?? '',
                    $row['no_berkas'] ?? ''
                ]);
                $success++;
                
                if ($processed % 10 == 0) {
                    echo "✅ Processed $processed records...<br>";
                    flush();
                }
                
            } catch (PDOException $e) {
                $errors++;
                echo "❌ Error on record $processed: " . $e->getMessage() . "<br>";
            }
        }
        
        $sqlite_pdo->commit();
        
        $end_time = microtime(true);
        $duration = $end_time - $start_time;
        
        echo "</div>";
        
        echo "<div style='color: green; font-weight: bold;'>🎯 SYNC COMPLETED!</div>";
        echo "<div><strong>Total Processed:</strong> $processed</div>";
        echo "<div><strong>Success:</strong> $success</div>";
        echo "<div><strong>Errors:</strong> $errors</div>";
        echo "<div><strong>Duration:</strong> " . number_format($duration, 2) . " seconds</div>";
        
        // Verify results
        $stmt = $sqlite_pdo->query("SELECT COUNT(*) FROM arsip");
        $final_count = $stmt->fetchColumn();
        echo "<div><strong>Final SQLite Count:</strong> $final_count records</div>";
        
        // Check file size
        if (file_exists($sqlite_path)) {
            $file_size = filesize($sqlite_path);
            echo "<div><strong>SQLite File Size:</strong> " . number_format($file_size / 1024, 2) . " KB</div>";
        }
        
    } catch (Exception $e) {
        echo "<div style='color: red; font-weight: bold;'>❌ ERROR: " . $e->getMessage() . "</div>";
    }
    
} else {
    echo "<div style='color: blue;'>ℹ️ Click button below to test sync process</div>";
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Test Sync Full</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .btn { background: #007bff; color: white; padding: 15px 30px; border: none; border-radius: 5px; font-size: 16px; cursor: pointer; }
        .btn:hover { background: #0056b3; }
        .btn:disabled { background: #6c757d; cursor: not-allowed; }
    </style>
</head>
<body>
    <form method="POST" id="testForm">
        <button type="submit" name="test_sync" class="btn" id="testBtn">
            🚀 Test Full Sync Process (50 records)
        </button>
    </form>
    
    <script>
        document.getElementById('testForm').addEventListener('submit', function() {
            const btn = document.getElementById('testBtn');
            btn.innerHTML = '⏳ Processing... Please wait';
            btn.disabled = true;
        });
    </script>
    
    <hr>
    <p><a href="sync-sipp-to-sqlite.php">← Back to Main Sync</a> | <a href="debug-sync.php">Debug Sync</a></p>
</body>
</html>
