<?php
class BukkuContact{
  
    // database connection
    private $conn;
    
    //api properties
    private $bearerToken;
    private $baseUrl;
    
    public $input;
    
    // constructor with $bBT as bearerToken
    public function __construct($bBT, $bUrl, $db){
        $this->bearerToken = $bBT;
        $this->baseUrl = $bUrl;
        $this->conn = $db;
    }
    
    function getAccType() {
    $query = "SELECT accType FROM idList WHERE username= '".$this->input->username."' ";
    $result = mysqli_query($this->conn, $query);
    if ($row = mysqli_fetch_assoc($result)) {
        return $row['accType'];
    }
    return;
    }
    
    function addData() {
    
    switch ($this->input->accType){
            case 'coach':

                return $loadData = array (
                    'entity_type' => $this->input->entityType,
                    'legal_name' => $this->input->firstname . ' ' . $this->input->lastname ,
                    'group_ids' => array (3),
                    'contact_persons' => [[
                        "first_name" => $this->input->firstname,
                        "last_name" => $this->input->lastname,
                        "is_default_billing" => true,
                        "is_default_shipping" => false]],
                    'email' => $this->input->email,
                    'phone_no' => $this->input->contactNo,
                    'types' => array ('supplier')
                    );
                    
            case 'client':

                return $loadData = array (
                    'entity_type' => $this->input->entityType,
                    'legal_name' => $this->input->schoolName,
                    'contact_persons' => [[
                        "first_name" => $this->input->firstname,
                        "last_name" => $this->input->lastname,
                        "is_default_billing" => true,
                        "is_default_shipping" => false]],
                    'group_ids' => array (2),
                    'email' => $this->input->email,
                    'phone_no' => $this->input->picNo,
                    'types' => array ('customer'),
                    'addresses' => [[
                        'name' => $this->input->schoolName,
                        'street' => $this->input->schoolStreet,
                        'city' => $this->input->schoolCity,
                        'state' => $this->input->schoolState,
                        'postcode' => $this->input->schoolPostcode,
                        'county_code' => 'MY',
                        "is_default_billing" => true,
                        "is_default_shipping"=> false
                        ]]
                    );
                    
            case 'customer':
                
                $address = explode(",", $this->area);

                return $loadData = array (
                    'entity_type' => $this->input->entityType,
                    'legal_name' => $this->input->firstname . ' ' . $this->input->lastname ,
                    'contact_persons' => array(
                        array(
                            "first_name" => $this->input->firstname,
                            "last_name" => $this->input->lastname,
                            'is_default_billing' => true,
                            'is_default_shipping' => false
                            )
                        ),
                    'group_ids' => array (4),
                    'email' => $this->input->email,
                    'phone_no' => $this->input->contactNo,
                    'types' => array ('customer'),
                    'addresses' => array (
                        'city' => $address[0],
                        'state' => $address[1],
                        'county_code' => 'MY',
                        "is_default_billing" => true,
                        "is_default_shipping"=> false
                        )
                    );
        }
    }

    function createContact(){
        
        $endpoint = '/contacts';
        $apiUrl = $this->baseUrl . $endpoint;
        
        $data = $this->addData();
        
        $jsonData = json_encode($data, JSON_PRETTY_PRINT);
        
        //echo $jsonData;
        
        // 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);
            // Get verbose log
            rewind($verbose);
            $verboseLog = stream_get_contents($verbose);
            //echo "Verbose information:\n" . $httpCode;
            return false;
        } else {
            
            if ($httpCode >= 200 && $httpCode < 300) {
                // Successful response
                //echo 'Response: ' . $response;
                return $response;
            } 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);
    }
    
    function updateData() {
    
    switch ($this->input->accType){
            case 'coach':

                return $loadData = array (
                    'entity_type' => $this->input->entity_type,
                    'legal_name' => $this->input->firstname . ' ' . $this->input->lastname ,
                    'group_ids' => array (3),
                    'contact_persons' => [[
                        "first_name" => $this->input->firstname,
                        "last_name" => $this->input->lastname,
                        "is_default_billing" => true,
                        "is_default_shipping" => false]],
                    'email' => $this->input->email,
                    'phone_no' => $this->input->contactNo,
                    'types' => array ('supplier')
                    );
                    
            case 'client':

                $address = explode(", ", $this->input->schoolAddress);
                
                return $loadData = array (
                    'entity_type' => $this->input->entity_type,
                    'legal_name' => $this->input->schoolName,
                    'contact_persons' => [[
                        "first_name" => $this->input->firstname,
                        "last_name" => $this->input->lastname,
                        "is_default_billing" => true,
                        "is_default_shipping" => false]],
                    'group_ids' => array (2),
                    'email' => $this->input->email,
                    'phone_no' => $this->input->picNo,
                    'types' => array ('customer'),
                    'addresses' => [[
                        'name' => $this->input->schoolName,
                        'street' => $address[0]. ' ' . $address[1],
                        'city' => $address[3],
                        'state' => $address[4],
                        'postcode' => $address[2],
                        'county_code' => 'MY',
                        "is_default_billing" => true,
                        "is_default_shipping"=> false
                        ]]
                    );
                    
            case 'customer':
                
                $address = explode(",", $this->area);

                return $loadData = array (
                    'entity_type' => $this->input->entity_type,
                    'legal_name' => $this->input->firstname . ' ' . $this->input->lastname ,
                    'contact_persons' => array(
                        array(
                            "first_name" => $this->input->firstname,
                            "last_name" => $this->input->lastname,
                            'is_default_billing' => true,
                            'is_default_shipping' => false
                            )
                        ),
                    'group_ids' => array (4),
                    'email' => $this->input->email,
                    'phone_no' => $this->input->contactNo,
                    'types' => array ('customer'),
                    'addresses' => array (
                        'city' => $address[0],
                        'state' => $address[1],
                        'county_code' => 'MY',
                        "is_default_billing" => true,
                        "is_default_shipping"=> false
                        )
                    );
        }
    }

    function updateContact(){
        
        $endpoint = '/contacts/'. $this->input->bukkuID;
        $apiUrl = $this->baseUrl . $endpoint;
        
        $data = $this->updateData();
        
        $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_CUSTOMREQUEST, 'PUT');
        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);
            // Get verbose log
            rewind($verbose);
            $verboseLog = stream_get_contents($verbose);
            echo "Verbose information:\n" . $httpCode;
            return false;
        } else {
            
            if ($httpCode >= 200 && $httpCode < 300) {
                return $response;
            } else {
                // Error response
                echo 'HTTP Status Code: ' . $httpCode . "\n";
                // Attempt to parse error message from response
                $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);
    }
    
}
?>