<?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;
}

$peminjaman_id = intval($_POST['peminjaman_id'] ?? 0);
$doc_index = intval($_POST['index'] ?? 0);

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

try {
    // Get current history
    $stmt = $db->prepare("SELECT dokumen_history_json FROM peminjaman WHERE id = ?");
    $stmt->execute([$peminjaman_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$row) {
        echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan']);
        exit;
    }
    
    $historyJson = $row['dokumen_history_json'] ?? null;
    $documents = $historyJson ? json_decode($historyJson, true) : [];
    
    if (!isset($documents[$doc_index])) {
        echo json_encode(['success' => false, 'message' => 'Dokumen tidak ditemukan']);
        exit;
    }
    
    // Delete physical file
    $filePath = $documents[$doc_index]['path'];
    if (file_exists($filePath)) {
        @unlink($filePath);
    }
    
    // Remove from array
    array_splice($documents, $doc_index, 1);
    
    // Update database
    if (count($documents) > 0) {
        $latest = end($documents);
        $updateStmt = $db->prepare("UPDATE peminjaman SET dokumen_path = ?, dokumen_keterangan = ?, dokumen_upload_at = ?, dokumen_history_json = ? WHERE id = ?");
        $updateStmt->execute([$latest['path'], $latest['keterangan'], $latest['uploaded_at'], json_encode($documents), $peminjaman_id]);
    } else {
        $updateStmt = $db->prepare("UPDATE peminjaman SET dokumen_path = NULL, dokumen_keterangan = NULL, dokumen_upload_at = NULL, dokumen_history_json = NULL WHERE id = ?");
        $updateStmt->execute([$peminjaman_id]);
    }
    
    echo json_encode(['success' => true, 'message' => 'Dokumen berhasil dihapus']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Gagal menghapus: ' . $e->getMessage()]);
}
