<?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 current dokumen path
    $stmt = $db->prepare("SELECT dokumen_path FROM peminjaman 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']);
    }
    
    // Update database
    $updateStmt = $db->prepare("UPDATE peminjaman SET dokumen_path = NULL, dokumen_keterangan = NULL, dokumen_upload_at = NULL WHERE id = ?");
    $updateStmt->execute([$id]);
    
    echo json_encode(['success' => true, 'message' => 'Dokumen berhasil dihapus']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Gagal menghapus: ' . $e->getMessage()]);
}
