<?php
/**
 * Debug Sync Process - Untuk melihat step by step apa yang terjadi
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h3>Debug Sync Process</h3>";

// Cek apakah POST sync diterima
if (isset($_POST['sync'])) {
    echo "<div style='color: green;'>✅ POST['sync'] diterima!</div>";
} else {
    echo "<div style='color: orange;'>⚠️ POST['sync'] tidak ada</div>";
}

// Konfigurasi database SIPP
$sipp_config = [
    'host' => '192.168.1.240',
    'dbname' => 'sippbaco',
    'username' => 'pnwtp',
    'password' => 'pnwtp2019',
    'port' => 3306
];

$sqlite_path = 'data/sipp_sync.sqlite';

echo "<h4>1. Test Koneksi SIPP</h4>";
try {
    $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);
    
    echo "<div style='color: green;'>✅ Koneksi SIPP: BERHASIL</div>";
    
    // Test query
    $stmt = $sipp_pdo->query("SELECT COUNT(*) FROM arsip");
    $count = $stmt->fetchColumn();
    echo "<div style='color: green;'>✅ Total records di SIPP: " . number_format($count) . "</div>";
    
    // Test ambil 1 record
    $stmt = $sipp_pdo->query("SELECT * FROM arsip LIMIT 1");
    $sample = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($sample) {
        echo "<div style='color: blue;'>📋 Sample data columns: " . implode(', ', array_keys($sample)) . "</div>";
    } else {
        echo "<div style='color: red;'>❌ Tidak ada data sample</div>";
    }
    
} catch (PDOException $e) {
    echo "<div style='color: red;'>❌ Koneksi SIPP: GAGAL - " . $e->getMessage() . "</div>";
}

echo "<h4>2. Test SQLite</h4>";
try {
    // Buat direktori jika belum ada
    $dir = dirname($sqlite_path);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
        echo "<div style='color: orange;'>📁 Directory '$dir' dibuat</div>";
    }
    
    $sqlite_pdo = new PDO("sqlite:$sqlite_path");
    $sqlite_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "<div style='color: green;'>✅ Koneksi SQLite: BERHASIL</div>";
    echo "<div>📍 File path: " . realpath($sqlite_path) . "</div>";
    echo "<div>📏 File size: " . number_format(filesize($sqlite_path)) . " bytes</div>";
    
    // Cek tabel arsip
    $stmt = $sqlite_pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='arsip'");
    $table_exists = $stmt->fetch();
    
    if ($table_exists) {
        echo "<div style='color: green;'>✅ Tabel arsip: ADA</div>";
        
        $stmt = $sqlite_pdo->query("SELECT COUNT(*) FROM arsip");
        $count = $stmt->fetchColumn();
        echo "<div style='color: blue;'>📊 Records di SQLite: " . number_format($count) . "</div>";
    } else {
        echo "<div style='color: orange;'>⚠️ Tabel arsip: BELUM ADA</div>";
    }
    
} catch (PDOException $e) {
    echo "<div style='color: red;'>❌ SQLite error: " . $e->getMessage() . "</div>";
}

if (isset($_POST['sync'])) {
    echo "<h4>3. Test Sync Process</h4>";
    
    try {
        // Buat tabel arsip
        $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;'>✅ Tabel arsip dibuat/sudah ada</div>";
        
        // Test query SIPP dengan LIMIT
        $sql = "SELECT * FROM arsip LIMIT 5";
        $stmt = $sipp_pdo->prepare($sql);
        $stmt->execute();
        
        $processed = 0;
        $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);
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $processed++;
            echo "<div style='color: blue;'>📝 Processing record $processed: " . ($row['nomor_perkara'] ?? 'N/A') . "</div>";
            
            try {
                $insert_stmt->execute([
                    $row['nomor_perkara'] ?? '',
                    $row['nomor_arsip'] ?? '',
                    $row['no_ruang'] ?? '',
                    $row['no_lemari'] ?? '',
                    $row['no_rak'] ?? '',
                    $row['no_berkas'] ?? ''
                ]);
                echo "<div style='color: green;'>  ✅ Inserted successfully</div>";
            } catch (PDOException $e) {
                echo "<div style='color: red;'>  ❌ Insert error: " . $e->getMessage() . "</div>";
            }
        }
        
        echo "<div style='color: green;'>🎯 Total processed: $processed records</div>";
        
        // Cek hasil
        $stmt = $sqlite_pdo->query("SELECT COUNT(*) FROM arsip");
        $final_count = $stmt->fetchColumn();
        echo "<div style='color: green;'>📊 Final SQLite count: " . number_format($final_count) . "</div>";
        
    } catch (Exception $e) {
        echo "<div style='color: red;'>❌ Sync error: " . $e->getMessage() . "</div>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Debug Sync</title>
</head>
<body>
    <hr>
    <form method="POST">
        <button type="submit" name="sync" style="background: blue; color: white; padding: 10px;">Test Sync Process</button>
    </form>
    
    <hr>
    <a href="sync-sipp-to-sqlite.php">← Kembali ke Sync Page</a>
</body>
</html>
