<?php
require 'db.php';

echo "Menambahkan kolom untuk upload dokumen...\n";

try {
    // Check if columns already exist
    $stmt = $db->query("PRAGMA table_info(peminjaman)");
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $columnNames = array_column($columns, 'name');
    
    $needsUpdate = false;
    
    if (!in_array('dokumen_path', $columnNames)) {
        echo "- Menambahkan kolom dokumen_path...\n";
        $db->exec("ALTER TABLE peminjaman ADD COLUMN dokumen_path TEXT");
        $needsUpdate = true;
    } else {
        echo "- Kolom dokumen_path sudah ada\n";
    }
    
    if (!in_array('dokumen_keterangan', $columnNames)) {
        echo "- Menambahkan kolom dokumen_keterangan...\n";
        $db->exec("ALTER TABLE peminjaman ADD COLUMN dokumen_keterangan TEXT");
        $needsUpdate = true;
    } else {
        echo "- Kolom dokumen_keterangan sudah ada\n";
    }
    
    if (!in_array('dokumen_upload_at', $columnNames)) {
        echo "- Menambahkan kolom dokumen_upload_at...\n";
        $db->exec("ALTER TABLE peminjaman ADD COLUMN dokumen_upload_at DATETIME");
        $needsUpdate = true;
    } else {
        echo "- Kolom dokumen_upload_at sudah ada\n";
    }
    
    if ($needsUpdate) {
        echo "\n✓ Kolom berhasil ditambahkan!\n";
    } else {
        echo "\n✓ Semua kolom sudah ada, tidak perlu update.\n";
    }
    
    // Create upload directory
    $uploadDir = 'uploads/dokumen/';
    if (!is_dir($uploadDir)) {
        if (mkdir($uploadDir, 0755, true)) {
            echo "✓ Direktori upload berhasil dibuat: $uploadDir\n";
        } else {
            echo "✗ Gagal membuat direktori upload\n";
        }
    } else {
        echo "✓ Direktori upload sudah ada\n";
    }
    
    // Create .htaccess to prevent direct access to uploads
    $htaccessPath = 'uploads/.htaccess';
    if (!file_exists($htaccessPath)) {
        $htaccessContent = "# Protect uploads directory\n";
        $htaccessContent .= "Options -Indexes\n";
        if (file_put_contents($htaccessPath, $htaccessContent)) {
            echo "✓ File .htaccess berhasil dibuat\n";
        }
    }
    
    echo "\n=== SELESAI ===\n";
    echo "Fitur upload dokumen siap digunakan!\n";
    
} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
