<?php
class BukkuInvoice{

    //api properties
    private $bearerToken;
    private $baseUrl;
    
    public $input;
    
    
    // constructor with $bBT as bearerToken
    public function __construct($bBT, $bUrl){
        $this->bearerToken = $bBT;
        $this->baseUrl = $bUrl;
    }
    
    function addData() {
        // Initialize an array to hold the processed items
        $processedItems = array();

        // Helper function to find the index of an entry by program name
        function findProgramIndex($processedItems, $programName) {
            foreach ($processedItems as $index => $item) {
                if (isset($item['description']) && strpos($item['description'], 'Program Name: ' . $programName) !== false) {
                    return $index;
                }
            }
            return false;
        }   
        
        // Iterate through each course
        foreach ($this->input->requestedCourseList as $course) {
            $programName = $course->programName;
            $existingIndex = findProgramIndex($processedItems, $programName);
            
            if ($existingIndex !== false) {
                // If the program name exists, add to the second place of the existing entry
                // The second place is the index immediately following the subtitle entry
                array_splice($processedItems, $existingIndex + 1, 0, array([
                    "type" => null,
                    "account_id" => $course->salesAccountID,
                    "description" => $course->sessionDesc,
                    "service_date" => (new DateTime($course->startTime))->format('Y-m-d'),
                    "product_id" => $course->productID,
                    "product_unit_id" => $course->sessionCostID,
                    "location_id" => null,
                    "unit_price" => $course->sessionCost,
                    "quantity" => $course->sessionCount,
                    "discount" => null,
                    "tax_code_id" => null
                    ]));
                
            } else {
                // If the program name does not exist, add the subtitle and detailed entries
                $processedItems[] = [
                    "type" => 'subtitle',
                    "description" => 'Program Name: ' . $programName
                    ];
                $processedItems[] = [
                    "type" => null,
                    "account_id" => $course->salesAccountID,
                    "description" => $course->sessionDesc,
                    "service_date" => (new DateTime($course->startTime))->format('Y-m-d'),
                    "product_id" => $course->productID,
                    "product_unit_id" => $course->sessionCostID,
                    "location_id" => null,
                    "unit_price" => $course->sessionCost,
                    "quantity" => $course->sessionCount,
                    "discount" => null,
                    "tax_code_id" => null
                    ];
                $processedItems[] = [
                    "type" => 'subtotal',
                    "description" => 'Program Name: ' . $programName
                    ];
            }
        }
        
        return $loadData = array (
                    'contact_id' => $this->input->bukkuID,
                    'payment_mode' => $this->input->payment_mode,
                    'term_items' => $this->input->term_items,
                    'date' => date('Y-m-d'),
                    'currency_code' => 'MYR',
                    'exchange_rate' => 1,
                    'billing_party' => $this->input->billing_party,
                    'title' => 'INVOICE',
                    'remarks' => 'Thank you for your interest in our service. Kindly indicate your acceptance for this quotation soon!',
                    'tax_mode' => 'exclusive',
                    'form_items' => $processedItems,
                    "status" => "ready",
                    'email' => array(
                        "to_addresses" => [$this->input->email],
                        "cc_addresses" => ["support@superwelljuniors.com"],
                        "reply_to_address" => "support@superwelljuniors.com",
                        "subject" => "Superwell Invoice",
                        "attach_pdf"=> true,
                        "form_design_id"=> 1
                        )
                    );
    }

    function createInvoice(){
        
        $endpoint = '/sales/invoices';
        $apiUrl = $this->baseUrl . $endpoint;
        
        $data = $this->addData();
        
        $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);
            // 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
                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);
    }
    
    function getInvoices($invID){
        $endpoint = '/sales/invoices/';
        $apiUrl = $this->baseUrl . $endpoint . $invID;
        
        // 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);
        // 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
                return json_decode($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);
    }

}
?>