<?php

namespace App\Helpers;

use App\Contact;
use App\Product;
use Illuminate\Support\Facades\Log;

class TimsHelper
{
    // public static $etimsUrl = "http://localhost:8888/api/v1";
    public static $etimsUrl = "https://deitax.deitiestech.com/api/v1";

    public static $username = "admin";
    public static $password = "aDmiN@2024";

    public static function getItems()
    {
        $credentials = base64_encode(self::$username.':'.self::$password);
        $endpoint = '/items';
        $url = self::$etimsUrl.$endpoint;

        $curl = curl_init();

        curl_setopt_array(
            $curl, 
            [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                // CURLOPT_USERPWD => self::$username.':'.self::$password
                CURLOPT_HTTPHEADER => [
                    "Authorization: Basic ".$credentials,
                    'Content-Type: application/json',
                    'Accept: application/json',
                ],
            ]
        );

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            Log::error('cURL error: ' . curl_error($curl));
        } else {
            return $response;
        }

        curl_close($curl);

    }

    public static function getItemByCode($code)
    {
        $credentials = base64_encode(self::$username.':'.self::$password);
        $endpoint = '/items/'.$code;
        $url = self::$etimsUrl.$endpoint;

        $curl = curl_init();

        curl_setopt_array(
            $curl, 
            [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    "Authorization: Basic ".$credentials,
                    'Content-Type: application/json',
                    'Accept: application/json',
                ],
            ]
        );

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            Log::error('cURL error: ' . curl_error($curl));
        } else {
            Log::alert("Item Obtained!");
            Log::alert($response);
            return $response;
        }

        curl_close($curl);
    }
    
    public static function storeItem($name, $countryCode, $unitPrice, $itemTypeCode,
    $taxCode, $quantityUnitCode, $packagingUnitCode, $itemClassCode, $initialStock = 0)
    {
        $endpoint = '/items';
        $url = self::$etimsUrl.$endpoint;
        $credentials = base64_encode(self::$username.':'.self::$password);
        
        // $url = 'https://deitax.deitiestech.com/api/v1/items';
        // $username = 'admin';
        // $password = 'aDmiN@2024';

        $body = json_encode([
            "name" => $name,
            "orgCountryCode" => $countryCode,
            "unitPrice" => intval($unitPrice),
            "itemTypeCode" => $itemTypeCode,
            "taxCode" => $taxCode,
            "qtyUnitCode" => $quantityUnitCode,
            "pkgUnitCode" => $packagingUnitCode,
            "itemClassCode" => $itemClassCode,
            "initialStock" => intval($initialStock)
        ]);

        // Log::info($credentials);
        Log::info($body);

        $curl = curl_init();

        curl_setopt_array(
            $curl, 
            [
                CURLOPT_URL => $url,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $body,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    "Authorization: Basic ".$credentials,
                    'Content-Type: application/json',
                    'Accept: application/json',
                ],
            ]
        );

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            Log::error('cURL error: ' . curl_error($curl));
        } else {
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            Log::info("HTTP Code: " . $httpCode);
            // Log::info("Response: " . $response);
            
            if ($httpCode >= 200 && $httpCode < 300) {
                Log::notice($name . " Successfully Registered!");
                Log::info($response);
                return $response;
            } else {
                Log::error('Error response: ' . $response);
            }
        }

        curl_close($curl);
        return false;
    }

    public static function updateItem($product, $name, $countryCode, $unitPrice, $itemTypeCode,
    $taxCode, $quantityUnitCode, $packagingUnitCode, $itemClassCode, $stock = 0)
    {
        $endpoint = '/items/'.$product->item_code;
        $url = self::$etimsUrl.$endpoint;
        $credentials = base64_encode(self::$username.':'.self::$password);
        
        // $url = 'https://deitax.deitiestech.com/api/v1/items/'.$product->item_code;
        // $username = 'admin';
        // $password = 'aDmiN@2024';
        // $credentials = base64_encode($username.':'.$password);

        $body = json_encode([
            "name" => $name,
            "orgCountryCode" => $countryCode,
            "unitPrice" => intval($unitPrice),
            "itemTypeCode" => $itemTypeCode,
            "taxCode" => $taxCode,
            "qtyUnitCode" => $quantityUnitCode,
            "pkgUnitCode" => $packagingUnitCode,
            "itemClassCode" => $itemClassCode,
            "stock" => intval($stock)
        ]);

        Log::info($credentials);
        Log::info($body);

        $curl = curl_init();

        curl_setopt_array(
            $curl, 
            [
                CURLOPT_URL => $url,
                CURLOPT_CUSTOMREQUEST => 'PUT',
                CURLOPT_POSTFIELDS => $body,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    "Authorization: Basic ".$credentials,
                    'Content-Type: application/json',
                    'Accept: application/json',
                ],
            ]
        );

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            Log::error('cURL error: ' . curl_error($curl));
        } else {
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            Log::info("HTTP Code: " . $httpCode);
            // Log::info("Response: " . $response);
            
            if ($httpCode >= 200 && $httpCode < 300) {
                Log::notice($name . " Successfully Updated!");
                Log::info($response);
                return $response;
            } else {
                Log::error('Error response: ' . $response);
            }
        }

        curl_close($curl);
        return false;
    }

    public static function deleteItem($product)
    {
        $endpoint = '/items/'.$product->item_code;
        $url = self::$etimsUrl.$endpoint;
        $credentials = base64_encode(self::$username.':'.self::$password);

        // $url = 'https://deitax.deitiestech.com/api/v1/items/'.$product->item_code;
        // $username = 'admin';
        // $password = 'aDmiN@2024';
        // $credentials = base64_encode($username.':'.$password);

        $curl = curl_init();

        curl_setopt_array(
            $curl, 
            [
                CURLOPT_URL => $url,
                CURLOPT_CUSTOMREQUEST => 'DELETE',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    "Authorization: Basic ".$credentials,
                    'Content-Type: application/json',
                    'Accept: */*',
                ],
            ]
        );

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            Log::error('cURL error: ' . curl_error($curl));
        } else {
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            Log::info("HTTP Code: " . $httpCode);
            // Log::info("Response: " . $response);
            
            if ($httpCode >= 200 && $httpCode < 300) {
                Log::notice($product->name . " Successfully Deleted!");
                Log::info($response);
                return $response;
            } else {
                Log::error('Error response: ' . $response);
            }
        }

        curl_close($curl);
        return false;
    }

    public static function genInvoice($transaction, $items)
    {
        $endpoint = '/invoices';
        $url = self::$etimsUrl.$endpoint;
        $credentials = base64_encode(self::$username.':'.self::$password);
        
        $itemList = [];
        $totalAmount = 0;

        foreach ($items as $item) {
            $product = Product::find($item['product_id']);
            $itemCode = $product->item_code;
            $qty = floatval(str_replace(",","",$item['quantity']));
            $unitPrice = floatval(str_replace(",","",$item['unit_price_inc_tax']));
            $amount = floatval($qty*$unitPrice);
            $totalAmount += $amount;

            $encodedItem = [
                "itemCode" => $itemCode,
                "qty" => $qty,
                "pkg" => 0,
                "unitPrice" => $unitPrice,
                "amount" => $amount,
                "discountAmount" => 0
            ];

            array_push($itemList, $encodedItem);
        }

        

        $body = json_encode([
            "traderInvoiceNo"=>  $transaction->invoice_no ?? $transaction->id,
            "totalAmount" => $totalAmount,
            "paymentType" => "01",
            "salesTypeCode" => "N",
            "receiptTypeCode" => "S",
            "salesStatusCode" => "01",
            "salesDate" => date("YmdHis"),
            "currency" => "KES",
            "exchangeRate" => 1.0,
            "salesItems" => $itemList,
            "customerPin" => $transaction->contact->tax_number ?? ""
        ]);

        Log::info($body);

        $curl = curl_init();

        curl_setopt_array(
            $curl, 
            [
                CURLOPT_URL => $url,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $body,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    "Authorization: Basic ".$credentials,
                    'Content-Type: application/json',
                    'Accept: application/json',
                ],
            ]
        );

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            Log::error('cURL error: ' . curl_error($curl));
        } else {
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            Log::info("HTTP Code: " . $httpCode);
            // Log::info("Response: " . $response);
            
            if ($httpCode >= 200 && $httpCode < 300) {
                Log::notice("Successfully Generated Invoice!");
                Log::info($response);
                return $response;
            } else {
                Log::error('Error response: ' . $response);
                return $response;
            }
        }

        curl_close($curl);
        return false;
    }

    public static function genCreditNoteInvoice($transaction, $items, $originalInvoiceNo)
    {
        $endpoint = '/invoices';
        $url = self::$etimsUrl.$endpoint;
        $credentials = base64_encode(self::$username.':'.self::$password);
        $itemList = [];
        $totalAmount = 0;

        foreach ($items as $item) {
            $product = Product::find($item['id']);
            $itemCode = $product->item_code;
            $qty = floatval(str_replace(",","",$item['quantity']));
            $unitPrice = floatval(str_replace(",","",$item['unit_price_inc_tax']));
            $amount = floatval($qty*$unitPrice);
            $totalAmount += $amount;

            $encodedItem = [
                "itemCode" => $itemCode,
                "qty" => $qty,
                "pkg" => 0,
                "unitPrice" => $unitPrice,
                "amount" => $amount,
                "discountAmount" => 0
            ];

            array_push($itemList, $encodedItem);
        }

        $body = json_encode([
            "traderInvoiceNo"=>  $transaction->invoice_no ?? $transaction->id,
            "traderOrgInvoiceNo" => $originalInvoiceNo,
            "totalAmount" => $totalAmount,
            "paymentType" => "01",
            "salesTypeCode" => "N",
            "receiptTypeCode" => "R",
            "salesStatusCode" => "01",
            "salesDate" => date("YmdHis"),
            "currency" => "KES",
            "exchangeRate" => 1.0,
            "salesItems" => $itemList
        ]);

        Log::info($body);

        $curl = curl_init();

        curl_setopt_array(
            $curl, 
            [
                CURLOPT_URL => $url,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $body,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    "Authorization: Basic ".$credentials,
                    'Content-Type: application/json',
                    'Accept: application/json',
                ],
            ]
        );

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            Log::error('cURL error: ' . curl_error($curl));
        } else {
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            Log::info("HTTP Code: " . $httpCode);
            // Log::info("Response: " . $response);
            
            if ($httpCode >= 200 && $httpCode < 300) {
                Log::notice("Successfully Generated Credit Note Invoice!");
                Log::info($response);
                return $response;
            } else {
                Log::error('Error response: ' . $response);
            }
        }

        curl_close($curl);
        return false;
    }
}