<?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 {
    $bank_name = $_POST['bank_name'] ?? '';
    $bank_content = $_POST['bank_content'] ?? '';
    $edit_mode = $_POST['edit_mode'] ?? '0';
    $collaboration_id = $_POST['collaboration_id'] ?? '';
    
    // Validate required fields
    if (empty($bank_name) || empty($bank_content)) {
        echo json_encode(['success' => false, 'message' => 'Bank name and content are required']);
        exit;
    }
    
    // Read existing data
    $collab_file = '../collab.json';
    $existing_data = [];
    
    if (file_exists($collab_file)) {
        $existing_content = file_get_contents($collab_file);
        if (!empty($existing_content)) {
            $existing_data = json_decode($existing_content, true) ?? [];
        }
    }
    
    // Initialize collaborations array if it doesn't exist
    if (!isset($existing_data['collaborations'])) {
        $existing_data['collaborations'] = [];
    }
    
    // Handle edit mode
    if ($edit_mode === '1' && !empty($collaboration_id)) {
        // Editing existing collaboration
        if (!isset($existing_data['collaborations'][$collaboration_id])) {
            echo json_encode(['success' => false, 'message' => 'Collaboration not found']);
            exit;
        }
        
        $existing_collaboration = $existing_data['collaborations'][$collaboration_id];
        $image_path = $existing_collaboration['bank_image']; // Keep existing image by default
        
        // Handle file upload for edit mode
        if (isset($_FILES['bank_image']) && $_FILES['bank_image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../collab_uploads/';
            
            // Create directory if it doesn't exist
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $file_info = pathinfo($_FILES['bank_image']['name']);
            $file_extension = $file_info['extension'];
            
            // Generate unique filename
            $unique_filename = 'bank_' . uniqid() . '.' . $file_extension;
            $target_path = $upload_dir . $unique_filename;
            
            // Check if file is an image
            $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            if (!in_array(strtolower($file_extension), $allowed_types)) {
                echo json_encode(['success' => false, 'message' => 'Invalid file type. Only images are allowed.']);
                exit;
            }
            
            // Move uploaded file
            if (move_uploaded_file($_FILES['bank_image']['tmp_name'], $target_path)) {
                // Delete old image file if it exists
                if (!empty($existing_collaboration['bank_image']) && file_exists('../' . $existing_collaboration['bank_image'])) {
                    unlink('../' . $existing_collaboration['bank_image']);
                }
                $image_path = 'collab_uploads/' . $unique_filename;
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
                exit;
            }
        }
        
        // Update collaboration data
        $existing_data['collaborations'][$collaboration_id] = [
            'bank_name' => $bank_name,
            'bank_content' => $bank_content,
            'bank_image' => $image_path,
            'status' => $existing_collaboration['status'], // Keep existing status
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        $success_message = 'Bank collaboration updated successfully';
        
    } else {
        // Creating new collaboration
        $image_path = '';
        
        // Handle file upload for create mode
        // Handle file upload for create mode
        if (isset($_FILES['bank_image']) && $_FILES['bank_image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../collab_uploads/';
            
            // Create directory if it doesn't exist
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $file_info = pathinfo($_FILES['bank_image']['name']);
            $file_extension = $file_info['extension'];
            
            // Generate unique filename
            $unique_filename = 'bank_' . uniqid() . '.' . $file_extension;
            $target_path = $upload_dir . $unique_filename;
            
            // Check if file is an image
            $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            if (!in_array(strtolower($file_extension), $allowed_types)) {
                echo json_encode(['success' => false, 'message' => 'Invalid file type. Only images are allowed.']);
                exit;
            }
            
            // Move uploaded file
            if (move_uploaded_file($_FILES['bank_image']['tmp_name'], $target_path)) {
                $image_path = 'collab_uploads/' . $unique_filename;
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
                exit;
            }
        }
        
        // Generate unique ID for new collaboration
        $collaboration_id = 'collab_' . uniqid();
        
        // Deactivate all existing collaborations when creating a new one
        foreach ($existing_data['collaborations'] as $id => $collab) {
            $existing_data['collaborations'][$id]['status'] = 'inactive';
        }
        
        // Add new collaboration data with unique ID
        $existing_data['collaborations'][$collaboration_id] = [
            'bank_name' => $bank_name,
            'bank_content' => $bank_content,
            'bank_image' => $image_path,
            'status' => 'active', // New collaborations are active by default
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        $success_message = 'Bank collaboration created successfully';
    }
    
    // Save to JSON file
    if (file_put_contents($collab_file, json_encode($existing_data, JSON_PRETTY_PRINT))) {
        echo json_encode([
            'success' => true, 
            'message' => $success_message,
            'data' => $existing_data['collaborations'][$collaboration_id],
            'id' => $collaboration_id
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to save data']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
