<?php

function curlAlterClassFinware($class_data)
{

  try {

    $ch = curl_init();
    // errorreturn($temp_product_id);
    $curl_info = getWorkspaceUpdateClassCurlUrl();
    $url = $curl_info['url'];
    $api_signature = $curl_info['api_signature'];
    
    $payload = json_encode(array("class_data" => $class_data,"api_signature" => $api_signature));

    // Set the cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    // Attach encoded JSON string to the POST fields
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    // Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Execute the POST request
    $result = curl_exec($ch);
    // response status 1 success else return errormsg from the error reecived from curl object
    //   if ($result === false) {
    //     echo json_encode(array('status' => 1, 'errormsg' => 'cURL error'));
    //   }

    // Check if cURL executed successfully
    // Check for cURL errors
    if ($result === false) {
        // Get cURL error and return a JSON-encoded error response
        $error_msg = curl_error($ch);
        curl_close($ch);
        echo json_encode(['status' => 0, 'error' => 'cURL error: ' . $error_msg]);
        die();  // Stop further execution
    }
    // Decode the JSON response
    $data = json_decode($result, true);
    // print_r($data);die();
    if(isset($data['error']) && $data['error']) {
        errorreturn ($data['message']);
        die();
    } 

    if ($data !== null) {
          // Return the result in JSON format
    return $data;
    }
    // else {
    //     errorreturn('Workspace ID  or finware book data not found or Finware product not found for this user');
    // }
    
  

    // Close cURL resource
    curl_close($ch);
  } catch (Exception $e) {
    echo "Error: " . $e->getMessage();
  }
}

function getWorkspaceUpdateClassCurlUrl()
{
  $url = $GLOBALS['curl_url_finware'].'resources/external_requests/education_curl/curl_groups_ledgers/curl_update_finware_class_groups.php';

  return array('url' => $url, 'api_signature' => 'WR5yGWg6mZ');
}
