<?php
class BukkuPGroup{
  
    // database connection
    private $conn;
    
    //api properties
    private $bearerToken;
    private $baseUrl;
    
    public $programName;
    public $programID;
        
    // constructor with $bBT as bearerToken
    public function __construct($bBT, $bUrl, $db){
        $this->bearerToken = $bBT;
        $this->baseUrl = $bUrl;
        $this->conn = $db;
    }
    
    function createGroupData(){
        return array (
            'name' => $this->programName,
            'product_ids' => []
        );
    }
    
    function createProductGroup(){
        
        $endpoint = '/products/groups';
        $apiUrl = $this->baseUrl . $endpoint;
        
        $data = $this->createGroupData();
        
        $jsonData = json_encode($data, JSON_PRETTY_PRINT);
        
        // Initialize cURL session
        $ch = curl_init($apiUrl);
        
        if ($ch === false) {
            echo 'Failed to initialize cURL session.';
        }
        
        // Set cURL options
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        // Define headers
        $headers = array(
            "Authorization: Bearer " . $this->bearerToken,
            'Content-Type: application/json',
            'Accept: application/json', // Adding Accept header
            'Company-Subdomain: swjuniors' // Adding custom header
        );
        
        // Set the headers
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        // Enable verbose mode
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        $verbose = fopen('php://temp', 'w+');
        curl_setopt($ch, CURLOPT_STDERR, $verbose);
        
        // Execute cURL request and get response
        $response = curl_exec($ch);
        
        // Check HTTP status code
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if ($response === false) {
            echo 'cURL Error: ' . curl_error($ch);
            rewind($verbose);
            $verboseLog = stream_get_contents($verbose);
            echo "Verbose information:\n" . $httpCode;
            return false;
        } else {
            if ($httpCode >= 200 && $httpCode < 300) {
                $responseData = json_decode($response);
                return $responseData->group->id;
            } else {
                echo 'HTTP Status Code: ' . $httpCode . "\n";
                $responseData = json_decode($response, true);
                if (isset($responseData['error'])) {
                    echo 'Error Message: ' . $responseData['error'];
                } else {
                    echo 'Error: ' . $response;
                }
                return false;
            }
        }
        
        // Close cURL session
        curl_close($ch);
    }
}

?>