<?php

function curlBookCreate($book_info)
{

  try {

    $ch = curl_init();
    $curl_info = BookCreateCurlUrl();
    $url = $curl_info['url'];
    $api_signature = $curl_info['api_signature'];

    $payload = json_encode(array("book_info" => $book_info, "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);
    // print_r($result);die();
    // response status 1 success else return errormsg from the error reecived from curl object
    // Check if cURL executed successfully
   if ($result === false) {
    $error_msg = curl_error($ch);
    curl_close($ch);
    
    // Set the header for JSON content type
    header("Content-Type: application/json");
    echo json_encode(array('status' => 0, 'error' => 'cURL error: ' . $error_msg));
    die();
    }
    
    // print_r($result);die();
    $data = json_decode($result, true);
    
    if (isset($data['error']) && $data['error']) {
        errorreturn ($data['message']);
        die();
    } 
 
    if($data !== null) {
      $data = array("book_id" => $data['book_id']);
    } else {
      errorreturn('Workspace ID not found or Finware product not found for this user');
      // Handle JSON parsing error
    }
    // Return the result in JSON format
    return $data;

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

function BookCreateCurlUrl()
{
  $url = $GLOBALS['curl_url_finware'] . 'resources/external_requests/curl_inter_products/curl_book_creation.php';

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