<?php
require 'db.php';
require 'auth.php';
require_login();
require_admin(); // Hanya admin yang bisa hapus

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method tidak diizinkan']);
    exit;
}

$id = intval($_POST['id'] ?? 0);

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID tidak valid']);
    exit;
}

try {
    // Get dokumen info
    $stmt = $db->prepare("SELECT * FROM dokumen_history WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$row) {
        echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan']);
        exit;
    }
    
    // Delete physical file if exists
    if (!empty($row['dokumen_path']) && file_exists($row['dokumen_path'])) {
        @unlink($row['dokumen_path']);
    }
    
    // Delete from database
    $deleteStmt = $db->prepare("DELETE FROM dokumen_history WHERE id = ?");
    $deleteStmt->execute([$id]);
    
    // Update peminjaman table - set to latest remaining document or null
    $latestStmt = $db->prepare("SELECT dokumen_path, dokumen_keterangan, uploaded_at FROM dokumen_history WHERE peminjaman_id = ? ORDER BY uploaded_at DESC LIMIT 1");
    $latestStmt->execute([$row['peminjaman_id']]);
    $latest = $latestStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($latest) {
        $updateStmt = $db->prepare("UPDATE peminjaman SET dokumen_path = ?, dokumen_keterangan = ?, dokumen_upload_at = ? WHERE id = ?");
        $updateStmt->execute([$latest['dokumen_path'], $latest['dokumen_keterangan'], $latest['uploaded_at'], $row['peminjaman_id']]);
    } else {
        $updateStmt = $db->prepare("UPDATE peminjaman SET dokumen_path = NULL, dokumen_keterangan = NULL, dokumen_upload_at = NULL WHERE id = ?");
        $updateStmt->execute([$row['peminjaman_id']]);
    }
    
    echo json_encode(['success' => true, 'message' => 'Dokumen berhasil dihapus']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Gagal menghapus: ' . $e->getMessage()]);
}
