<?php
require_once '../config/connection.php';
checkUserType(['superadmin']);

$id = (int)$_GET['id'];
$type = $_GET['type'] ?? 'asset';
$message = '';
$success = false;

// Validate parameters
if (!$id || !in_array($type, ['asset', 'admin', 'borrower'])) {
    header("Location: dashboard.php");
    exit();
}

try {
    $pdo->beginTransaction();
    
    if ($type == 'asset') {
        // Check if asset is currently borrowed
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM borrow_history WHERE asset_id = ? AND status = 'borrowed'");
        $stmt->execute([$id]);
        
        if ($stmt->fetchColumn() > 0) {
            $message = 'Asset tidak dapat dihapus karena sedang dipinjam!';
        } else {
            // Get asset info for logging
            $stmt = $pdo->prepare("SELECT asset_name, asset_number FROM assets WHERE id = ?");
            $stmt->execute([$id]);
            $asset = $stmt->fetch();
            
            if ($asset) {
                // Delete related borrow history first
                $stmt = $pdo->prepare("DELETE FROM borrow_history WHERE asset_id = ?");
                $stmt->execute([$id]);
                
                // Delete the asset
                $stmt = $pdo->prepare("DELETE FROM assets WHERE id = ?");
                $stmt->execute([$id]);
                
                $message = "Asset '{$asset['asset_name']}' ({$asset['asset_number']}) berhasil dihapus!";
                $success = true;
            } else {
                $message = 'Asset tidak ditemukan!';
            }
        }
        
    } elseif ($type == 'admin') {
        // Check if admin has active sessions or pending requests
        $stmt = $pdo->prepare("SELECT full_name, employee_id FROM admins WHERE id = ?");
        $stmt->execute([$id]);
        $admin = $stmt->fetch();
        
        if ($admin) {
            // Delete the admin
            $stmt = $pdo->prepare("DELETE FROM admins WHERE id = ?");
            $stmt->execute([$id]);
            
            $message = "Admin '{$admin['full_name']}' ({$admin['employee_id']}) berhasil dihapus!";
            $success = true;
        } else {
            $message = 'Admin tidak ditemukan!';
        }
        
    } elseif ($type == 'borrower') {
        // Check if borrower has active borrows
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM borrow_history WHERE borrower_employee_id = (SELECT employee_id FROM borrowers WHERE id = ?) AND status = 'borrowed'");
        $stmt->execute([$id]);
        
        if ($stmt->fetchColumn() > 0) {
            $message = 'Borrower tidak dapat dihapus karena masih memiliki peminjaman aktif!';
        } else {
            // Get borrower info
            $stmt = $pdo->prepare("SELECT full_name, employee_id FROM borrowers WHERE id = ?");
            $stmt->execute([$id]);
            $borrower = $stmt->fetch();
            
            if ($borrower) {
                // Update borrow history to remove reference
                $stmt = $pdo->prepare("UPDATE borrow_history SET borrower_employee_id = 'DELETED_USER' WHERE borrower_employee_id = ?");
                $stmt->execute([$borrower['employee_id']]);
                
                // Delete the borrower
                $stmt = $pdo->prepare("DELETE FROM borrowers WHERE id = ?");
                $stmt->execute([$id]);
                
                $message = "Borrower '{$borrower['full_name']}' ({$borrower['employee_id']}) berhasil dihapus!";
                $success = true;
            } else {
                $message = 'Borrower tidak ditemukan!';
            }
        }
    }
    
    $pdo->commit();
    
} catch (Exception $e) {
    $pdo->rollback();
    $message = 'Terjadi kesalahan: ' . $e->getMessage();
}

// Determine redirect URL
$redirect_urls = [
    'asset' => 'assets.php',
    'admin' => 'users.php',
    'borrower' => 'users.php'
];

$redirect_url = $redirect_urls[$type];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Result - Peminjaman Tools Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5',
                        'medium-gray': '#9CA3AF'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-soft-gray min-h-screen flex items-center justify-center">
    <div class="max-w-md mx-auto">
        <div class="bg-white rounded-2xl shadow-xl p-8 text-center">
            <!-- Icon -->
            <div class="mb-6">
                <?php if ($success): ?>
                <div class="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
                    <svg class="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                    </svg>
                </div>
                <?php else: ?>
                <div class="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center">
                    <svg class="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Title -->
            <h2 class="text-2xl font-bold text-gray-800 mb-4">
                <?php echo $success ? 'Berhasil Dihapus!' : 'Gagal Menghapus!'; ?>
            </h2>
            
            <!-- Message -->
            <p class="text-medium-gray mb-6">
                <?php echo $message; ?>
            </p>
            
            <!-- Actions -->
            <div class="space-y-3">
                <a href="<?php echo $redirect_url; ?>" 
                   class="w-full bg-dark-leaf hover:bg-green-600 text-white px-6 py-3 rounded-lg transition duration-200 font-semibold inline-block">
                    Kembali ke <?php echo $type == 'asset' ? 'Asset' : 'User'; ?> Management
                </a>
                <a href="dashboard.php" 
                   class="w-full bg-medium-gray hover:bg-gray-600 text-white px-6 py-3 rounded-lg transition duration-200 font-semibold inline-block">
                    Dashboard
                </a>
            </div>
        </div>
    </div>
    
    <script>
        // Auto redirect after 5 seconds if successful
        <?php if ($success): ?>
        setTimeout(function() {
            window.location.href = '<?php echo $redirect_url; ?>';
        }, 5000);
        <?php endif; ?>
    </script>
</body>
</html>