<?php
require_once __DIR__ . '/../../config/secure_bootstrap.php';

// Cek parameter ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error'] = 'ID dokumen tidak valid';
    header('Location: ../dokumen.php');
    exit;
}

try {
    $id = (int)$_GET['id'];
    
    // Ambil data dokumen
    $stmt = $pdo->prepare("SELECT * FROM documents WHERE id = ?");
    $stmt->execute([$id]);
    $doc = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$doc) {
        throw new Exception('Dokumen tidak ditemukan');
    }
    
    // Mulai transaksi
    $pdo->beginTransaction();
    
    try {
        // Hapus dari database
        $stmt = $pdo->prepare("DELETE FROM documents WHERE id = ?");
        $result = $stmt->execute([$id]);
        
        if (!$result) {
            throw new Exception('Gagal menghapus data dari database');
        }
        
        // Hapus file fisik jika ada
        if (!empty($doc['file_path'])) {
            $file_path = __DIR__ . '/../../' . $doc['file_path'];
            if (file_exists($file_path)) {
                if (!unlink($file_path)) {
                    // Log warning tapi tidak throw error
                    error_log("Warning: Gagal menghapus file fisik: " . $file_path);
                }
            }
        }
        
        // Commit transaksi
        $pdo->commit();
        
        // Log aktivitas (setelah commit)
        try {
            $log_stmt = $pdo->prepare("
                INSERT INTO activity_logs (user_id, action, description, created_at) 
                VALUES (?, 'delete_document', ?, NOW())
            ");
            $log_stmt->execute([
                $_SESSION['user_id'],
                "Menghapus dokumen: {$doc['title']}"
            ]);
        } catch (Exception $e) {
            // Log error tapi tidak perlu throw
            error_log("Error logging activity: " . $e->getMessage());
        }
        
        $_SESSION['success'] = 'Dokumen berhasil dihapus';
        
    } catch (Exception $e) {
        // Rollback
        $pdo->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    $_SESSION['error'] = $e->getMessage();
    
    // Log error
    error_log("Error dokumen_hapus.php: " . $e->getMessage());
}

header('Location: ../dokumen.php');
exit;