<?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'] ?? '';
    $new_status = $input['status'] ?? '';
    
    // Validate inputs
    if (empty($collaboration_id)) {
        echo json_encode(['success' => false, 'message' => 'Collaboration ID is required']);
        exit;
    }
    
    if (!in_array($new_status, ['active', 'inactive'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid status value']);
        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;
    }
    
    // If setting to active, first set all others to inactive
    if ($new_status === 'active') {
        foreach ($existing_data['collaborations'] as $id => $collab) {
            $existing_data['collaborations'][$id]['status'] = 'inactive';
        }
    }
    
    // Update the specific collaboration status
    $existing_data['collaborations'][$collaboration_id]['status'] = $new_status;
    $existing_data['collaborations'][$collaboration_id]['updated_at'] = date('Y-m-d H:i:s');
    
    // Save the updated data
    if (file_put_contents($collab_file, json_encode($existing_data, JSON_PRETTY_PRINT))) {
        $status_text = $new_status === 'active' ? 'activated' : 'deactivated';
        echo json_encode([
            'success' => true, 
            'message' => "Collaboration {$status_text} successfully",
            'status' => $new_status
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update status']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
