 <?php
  header('Content-Type: application/json');
  
  ini_set('error_log', __DIR__ . '/bug_report_response.log');
  file_put_contents(__DIR__ . '/bug_report_response.log', $logMessage, FILE_APPEND);

  
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   $apiKey = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjI5NjkzOTQ5OSwiYWFpIjoxMSwidWlkIjoyODU3NTM3MCwiaWFkIjoiMjAyMy0xMS0xN1QxMToyNjoyMy4wOTZaIiwicGVyIjoibWU6d3JpdGUiLCJhY3RpZCI6ODk5NjkyLCJyZ24iOiJ1c2UxIn0.QG7I33YsXwPrFACmKW6exmJrzqH2jmrbcmmoG38bs48';
    $boardId = 5536569530; // Replace with your board ID

    //file_put_contents(__DIR__ . '/raw_post_data.log', file_get_contents('php://input'), FILE_APPEND);
    $data = json_decode(file_get_contents('php://input'), true);
    
    
    // Extract itemNo from the data
    $itemNo2 = addslashes($data['itemNo']); // Use addslashes to escape any special characters
    $orderNo2 = addslashes($data['orderNo']); // Use addslashes to escape any special characters
    $customerName2 = addslashes($data['customerName']);
    $description2 = addslashes($data['description']);
    $serialNo2 = addslashes($data['serialNo']);
    $account2 = addslashes($data['account']);
    
    // Prepare the column values
    $columnValues = array(
        'item_no' => $itemNo2,
        'order_no8' => $orderNo2,
        'text' => $customerName2,
        'text2' => $description2,
        'text0' => $serialNo2, // Changed to 'text0' as per the new column ID in Monday.com
        'account' => $account2
    );
  
    
    
    // Encode the column values as JSON string
    $columnValuesJson = json_encode($columnValues);
    $ItemJson = json_encode($itemNo2);
    
    $bugreport = "Bugreport ";
    
    // Create a data array for the API request
    $data = array(
        'query' => 'mutation ($boardId: Int!, $itemName: String!, $columnValues: JSON!) { create_item (board_id: $boardId, item_name: $itemName, column_values: $columnValues) { id } }',
        'variables' => array(
            'boardId' => $boardId,
            'itemName' => $bugreport . $ItemJson,
            'columnValues' => $columnValuesJson
        )
    );

    $jsonData = json_encode($data);
    file_put_contents(__DIR__ . '/raw_post_data.log', file_get_contents('php://input'), FILE_APPEND);
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/json\r\nAuthorization: $apiKey",
            'method'  => 'POST',
            'content' => $jsonData,
        )
    );

    $context = stream_context_create($options);

    // Send the API request to Monday.com
    $result = file_get_contents('https://api.monday.com/v2', false, $context);

    // Handle the response
    $response = $result !== FALSE ? json_decode($result, true) : ['error' => 'Error making request to Monday.com API'];
   
    
    // Send the response
    
    echo json_encode($response);

   }
?>