<?php
// Get JSON POST data
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);

// Monday.com API URL for creating an item
$apiUrl = "https://api.monday.com/v2";
$apiKey = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjI5NjkzOTQ5OSwiYWFpIjoxMSwidWlkIjoyODU3NTM3MCwiaWFkIjoiMjAyMy0xMS0xN1QxMToyNjoyMy4wOTZaIiwicGVyIjoibWU6d3JpdGUiLCJhY3RpZCI6ODk5NjkyLCJyZ24iOiJ1c2UxIn0.QG7I33YsXwPrFACmKW6exmJrzqH2jmrbcmmoG38bs48';
$boardId = 5598953610; // Your specific board ID for orders

// Prepare data for Monday.com
$data = [
    'query' => 'mutation ($myItemName: String!, $columnVals: JSON!) { 
                    create_item (
                        board_id: ' . $boardId . ', 
                        item_name: $myItemName, 
                        column_values: $columnVals
                    ) { 
                        id 
                    } 
                }',
    'variables' => [
        'myItemName' => isset($decoded['user']) ? $decoded['user'] : $decoded['username'], // Use whichever is set
        'columnVals' => json_encode([
            'date4' => ['date' => $decoded['date']],
            'text_1' => $decoded['time'],
            'text0' => isset($decoded['type']) ? $decoded['type'] : $decoded['activityType'], // Use whichever is set
            'text_11' => isset($decoded['realname']) ? $decoded['realname'] : $decoded['popRealname'], // Use whichever is set
            'text' => $decoded['details']
        ])
    ]
];

// Use cURL to send the POST request
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: ' . $apiKey]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

// Check for successful response
if ($result === false) {
    // Handle error
    echo "Error: " . curl_error($ch);
} else {
    // Decode the response
    $response = json_decode($result, true);
    
    // Check if response contains errors
    if (isset($response['errors'])) {
        // Handle API errors
        echo "API Error: " . print_r($response['errors'], true);
    } else {
        // API call successful, process further if needed
        echo "Log created successfully";
    }
}

?>
