<?php
require 'db.php';

echo "Menambahkan kolom untuk history dokumen (JSON format)...\n";

try {
    // Check if column already exists
    $stmt = $db->query("PRAGMA table_info(peminjaman)");
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $columnNames = array_column($columns, 'name');
    
    if (!in_array('dokumen_history_json', $columnNames)) {
        echo "- Menambahkan kolom dokumen_history_json...\n";
        $db->exec("ALTER TABLE peminjaman ADD COLUMN dokumen_history_json TEXT");
        echo "✓ Kolom berhasil ditambahkan!\n";
        
        // Migrate existing documents to JSON format (only if dokumen_path column exists)
        if (in_array('dokumen_path', $columnNames)) {
            echo "\nMemigrate dokumen yang sudah ada ke format JSON...\n";
            $stmt = $db->query("SELECT id, dokumen_path, dokumen_keterangan, dokumen_upload_at FROM peminjaman WHERE dokumen_path IS NOT NULL AND dokumen_path != ''");
            $existingDocs = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $migrated = 0;
            foreach ($existingDocs as $doc) {
                $history = [[
                    'path' => $doc['dokumen_path'],
                    'keterangan' => $doc['dokumen_keterangan'] ?? '',
                    'uploaded_by' => 'System Migration',
                    'uploaded_at' => $doc['dokumen_upload_at'] ?: date('Y-m-d H:i:s')
                ]];
                
                $updateStmt = $db->prepare("UPDATE peminjaman SET dokumen_history_json = ? WHERE id = ?");
                $updateStmt->execute([json_encode($history), $doc['id']]);
                $migrated++;
            }
            
            echo "✓ Berhasil migrate $migrated dokumen ke format JSON\n";
        } else {
            echo "! Kolom dokumen_path belum ada, skip migration\n";
            echo "  (Ini normal untuk instalasi baru)\n";
        }
    } else {
        echo "✓ Kolom dokumen_history_json sudah ada\n";
    }
    
    echo "\n=== SELESAI ===\n";
    echo "Sistem multiple upload dokumen siap digunakan!\n";
    echo "TIDAK perlu tabel baru, menggunakan kolom JSON.\n";
    
} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
