<?php
require 'db.php';

echo "Membuat tabel untuk history dokumen...\n";

try {
    // Create table for document history
    $sql = "CREATE TABLE IF NOT EXISTS dokumen_history (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        peminjaman_id INTEGER NOT NULL,
        dokumen_path TEXT NOT NULL,
        dokumen_keterangan TEXT,
        uploaded_by TEXT,
        uploaded_at DATETIME NOT NULL,
        FOREIGN KEY (peminjaman_id) REFERENCES peminjaman(id) ON DELETE CASCADE
    )";
    
    $db->exec($sql);
    echo "✓ Tabel dokumen_history berhasil dibuat!\n";
    
    // Migrate existing documents to history table
    echo "\nMemigrate dokumen yang sudah ada...\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) {
        $insertStmt = $db->prepare("INSERT INTO dokumen_history (peminjaman_id, dokumen_path, dokumen_keterangan, uploaded_by, uploaded_at) VALUES (?, ?, ?, ?, ?)");
        $uploadedAt = $doc['dokumen_upload_at'] ?: date('Y-m-d H:i:s');
        $insertStmt->execute([
            $doc['id'],
            $doc['dokumen_path'],
            $doc['dokumen_keterangan'],
            'System Migration',
            $uploadedAt
        ]);
        $migrated++;
    }
    
    echo "✓ Berhasil migrate $migrated dokumen ke tabel history\n";
    
    echo "\n=== SELESAI ===\n";
    echo "Tabel dokumen_history siap digunakan!\n";
    echo "Sistem sekarang mendukung multiple upload dokumen.\n";
    
} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
