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

// Check if the request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $collaboration_id = $input['collaboration_id'] ?? '';
    
    // Validate collaboration ID
    if (empty($collaboration_id)) {
        echo json_encode(['success' => false, 'message' => 'Collaboration ID is required']);
        exit;
    }
    
    $collab_file = '../collab.json';
    
    // Check if file exists
    if (!file_exists($collab_file)) {
        echo json_encode(['success' => false, 'message' => 'No collaboration data found']);
        exit;
    }
    
    // Read existing data
    $existing_content = file_get_contents($collab_file);
    $existing_data = json_decode($existing_content, true) ?? [];
    
    // Check if collaborations exist
    if (!isset($existing_data['collaborations']) || !isset($existing_data['collaborations'][$collaboration_id])) {
        echo json_encode(['success' => false, 'message' => 'Collaboration not found']);
        exit;
    }
    
    // Get the image path before deleting to remove the file
    $image_path = '';
    if (isset($existing_data['collaborations'][$collaboration_id]['bank_image'])) {
        $image_path = '../' . $existing_data['collaborations'][$collaboration_id]['bank_image'];
    }
    
    // Remove the collaboration data
    unset($existing_data['collaborations'][$collaboration_id]);
    
    // Delete the image file if it exists
    if (!empty($image_path) && file_exists($image_path)) {
        unlink($image_path);
    }
    
    // Save the updated data
    if (file_put_contents($collab_file, json_encode($existing_data, JSON_PRETTY_PRINT))) {
        echo json_encode([
            'success' => true, 
            'message' => 'Bank collaboration deleted successfully'
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update data file']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
