<?php
require 'db.php';
require 'auth.php';
require_login();
require_admin(); // Only admin can delete

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $type = $_POST['type'] ?? '';
    
    if ($id > 0) {
        try {
            // Check if record exists
            $check = $db->prepare("SELECT status FROM peminjaman WHERE id = ?");
            $check->execute([$id]);
            $current = $check->fetch(PDO::FETCH_ASSOC);
            
            if (!$current) {
                echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan']);
                exit;
            }
            
            // Different logic for returned items vs regular deletion
            if ($type === 'returned') {
                // Allow deletion of returned items (admin only)
                if ($current['status'] !== 'kembali') {
                    echo json_encode(['success' => false, 'message' => 'Hanya data yang sudah dikembalikan yang bisa dihapus permanen']);
                    exit;
                }
            } else {
                // Regular deletion - only allow dipinjam status
                if ($current['status'] !== 'dipinjam') {
                    echo json_encode(['success' => false, 'message' => 'Hanya data dengan status dipinjam yang bisa dihapus']);
                    exit;
                }
            }
            
            $stmt = $db->prepare("DELETE FROM peminjaman WHERE id = ?");
            $result = $stmt->execute([$id]);
            
            if ($result && $stmt->rowCount() > 0) {
                $message = ($type === 'returned') ? 'Data berkas yang sudah dikembalikan berhasil dihapus permanen' : 'Data berhasil dihapus';
                echo json_encode(['success' => true, 'message' => $message]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Gagal menghapus data']);
            }
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'ID tidak valid']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Method tidak diizinkan']);
}
exit;
?>
