Current File : /home/users/barii/public_html/finansenl.com.pl/wodki/admin/classes/the_api.php
<?php
require_once('/home/users/barii/public_html/finansenl.com.pl/wodki/mpdf/mpdf.php');
// THE (Mariusz) Allegro API functions 
// Created : 01/2024

    $servername = "67973.m.tld.pl";
    $username = "admin67973_etykiety";
    $password = "5BmF1MXif0";
    $dbname = "baza67973_etykiety";

    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }



function generateLabel($accessToken, $shipmentIds, $pageSize = "A6", $cutLine = false) {
    $curl = curl_init();
    $postData = json_encode([
        "shipmentIds" => $shipmentIds,
        "pageSize" => $pageSize,
        "cutLine" => $cutLine
    ]);

    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.allegro.pl/shipment-management/label",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $accessToken",
            "Accept: application/octet-stream",
            "Content-Type: application/vnd.allegro.public.v1+json"
        ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
        return $response; 
    }
}


function getAllegroCheckoutForms($token, $offset = 0, $limit = null) {
    // Base URL for the API endpoint
    $url = 'https://api.allegro.pl/order/checkout-forms';

    // Append parameters to the URL if provided
    $queryParams = [
        'offset' => $offset,
        'status' => 'READY_FOR_PROCESSING' 
    ];
    
    if ($limit) {
        $queryParams['limit'] = $limit;
    }

    // Construct the final URL with query parameters
    $url .= '?' . http_build_query($queryParams);

    // Initialize cURL
    $ch = curl_init($url);

    // Set cURL options
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string

    // Execute cURL request and get the response
    $response = curl_exec($ch);

    $responseData = json_decode($response, true);
    return $responseData;
}

function getOrderEvents($token, $lastSeenEventId = null, $limit = 500) {
    // Base URL for the API endpoint
    $url = 'https://api.allegro.pl/order/events';

    // Append parameters to the URL if provided
    $queryParams = [
        'limit' => $limit
    ];
    
    if ($lastSeenEventId) {
        $queryParams['from'] = $lastSeenEventId;
    }

    // Construct the final URL with query parameters
    $url .= '?' . http_build_query($queryParams);

    // Initialize cURL
    $ch = curl_init($url);

    // Set cURL options
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string

    // Execute cURL request and get the response
    $response = curl_exec($ch);

    $responseData = json_decode($response, true);
    return $responseData;
}


function displayShipmentDetails($accessToken, $shipmentId) {
    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.allegro.pl/shipment-management/shipments/$shipmentId",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $accessToken",
            "Accept: application/vnd.allegro.public.v1+json"
        ],
        CURLOPT_CUSTOMREQUEST => "GET" 

    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
        return $response;
    }
}

function displayShipmentStatus($accessToken, $shipmentId) {
    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.allegro.pl/shipment-management/shipments/create-commands/".$shipmentId,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $accessToken",
            "Accept: application/vnd.allegro.public.v1+json"
        ],
        CURLOPT_CUSTOMREQUEST => "GET" 

    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
         return json_decode($response, true);
    }
}

function getDeliveryServices($token) {
    $url = 'https://api.allegro.pl/shipment-management/delivery-services';

    $headers = [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json'
    ];

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }

    curl_close($ch);

    return json_decode($response, true);
}

function prettyPrint($variable) {
    $exported = var_export($variable, true);
    $pretty = preg_replace("/,/", ",\n", $exported);
    echo "<pre>" . $pretty . "</pre>";
}




function updateOrderStatus($checkoutFormId, $token, $status) {

    $url = 'https://api.allegro.pl/order/checkout-forms/' . $checkoutFormId . '/fulfillment';

    $data = json_encode(array("status" => $status));

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json',
        'Content-Type: application/vnd.allegro.public.v1+json'
    ));


    $response = curl_exec($ch);


    if (curl_errno($ch)) {
        throw new Exception(curl_error($ch));
    }


    curl_close($ch);

 
    return $response;
}



function createShipment($token, $shipping_method, $package_type="PACKAGE", $package_length="30", $package_width="20", $package_height="10", $package_weight="1", $send_point, $receiver_email = "", $receiver_name = "", $receiver_company = "", $receiver_street = "", $receiver_postcode = "", $receiver_city = "", $receiver_phone = "", $receiver_point = "") {
    $url = 'https://api.allegro.pl/shipment-management/shipments/create-commands';

if ($receiver_point != '') {
    $receiver_name = substr($receiver_name, 0, 30);
}

    $shipmentData = [
        "input" => [
            "deliveryMethodId" => getSpecificDeliveryMethodId($token, $shipping_method),
            "sender" => [
                "name" => "Grzegorz Mączyński",
                "company" => "Prolabel",
                "street" => "Mydlana 1",
                "postalCode" => "51-502",
                "city" => "Wrocław",
                "countryCode" => "PL",
                "email" => "biuro@prolabel.pl",
                "phone" => "512512661"
            ],
            "receiver" => [
                "name" => $receiver_name,
                "street" => $receiver_street,
                "streetNumber" => "",
                "postalCode" => $receiver_postcode,
                "city" => $receiver_city,
                "countryCode" => "PL",
                "email" => $receiver_email,
                "phone" => $receiver_phone,
            ],
            "pickup" => [
                "name" => "Grzegorz Mączyński",
                "company" => "Prolabel",
                "street" => "Mydlana 1",
                "postalCode" => "51-502",
                "city" => "Wrocław",
                "countryCode" => "PL",
                "email" => "biuro@prolabel.pl",
                "phone" => "512512661"
            ],                            
            "packages" => [
                [
                    "type" => $package_type,
                    "length" => ["value" => $package_length, "unit" => "CENTIMETER"],
                    "width" => ["value" => $package_width, "unit" => "CENTIMETER"],
                    "height" => ["value" => $package_height, "unit" => "CENTIMETER"],
                    "weight" => ["value" => $package_weight, "unit" => "KILOGRAMS"]
                ]
            ],
            "description" => "Fotomagnesy",
            "labelFormat" => "PDF",
        ]
    ];

    if ($receiver_point != '') {
        $shipmentData['input']['receiver']['point'] = $receiver_point;
    }
    if ($receiver_company != '') {
        $shipmentData['input']['receiver']['company'] = substr($receiver_company, 0, 30);
    }
    if ($send_point > 0) {
        $shipmentData['input']['pickup']['point'] = $send_point;
    }

    $headers = [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json',
        'Content-Type: application/vnd.allegro.public.v1+json'
    ];

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($shipmentData));

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }

    curl_close($ch);
    sleep(5);
    return json_decode($response, true);
}

function getSpecificDeliveryMethodId($token, $searchId) {
    $url = 'https://api.allegro.pl/shipment-management/delivery-services';

    $headers = [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
        curl_close($ch);
        return null;
    }

    curl_close($ch);

    $decodedResponse = json_decode($response, true);

    // Check if the services key exists in the response
    if (isset($decodedResponse['services'])) {
        // Iterate over each service in the services array
        foreach ($decodedResponse['services'] as $service) {
            // Check if this service's deliveryMethodId matches the searchId
            if (isset($service['id']['deliveryMethodId']) && $service['id']['deliveryMethodId'] == $searchId) {
                return $service['id']['deliveryMethodId']; // Return the entire service array if the ID matches
            }
        }
    }

    return null; // Return null if no matching service is found
}



function getAllegroCarriers($accessToken) {

    $url = "https://api.allegro.pl/order/carriers";


    $ch = curl_init($url);


    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.public.v1+json'
    ));


    $response = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);


    curl_close($ch);


    if ($status == 200) {

        $responseData = json_decode($response, true);
        return $responseData;
    } else {
 
        return "Error: " . $response;
    }
}
function getAllegroShipmentDetails($token, $checkoutFormId) {
    // Allegro API URL for getting shipment details
    $url = "https://api.allegro.pl/order/checkout-forms/{$checkoutFormId}/shipments";

    // Initialize cURL
    $ch = curl_init($url);

    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json'
    ]);

    // Execute the request
    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        return "cURL error: " . $error_msg;
    }

    // Get the HTTP response code
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // Close cURL session
    curl_close($ch);

    // Check if the request was successful (HTTP 200)
    if ($httpCode == 200) {
        return json_decode($response, true); // Return the decoded JSON response as an associative array
    } else {
        return "Error: Received HTTP code $httpCode. Response: " . $response;
    }
}

function createAllegroShipment($accessToken, $checkoutFormId, $shipmentData, $przewoznik, $numer_przesylki) {

    $url = "https://api.allegro.pl/order/checkout-forms/$checkoutFormId/shipments";

    $shipmentData = [
        'carrierId' => $przewoznik, 
        'waybill' => $numer_przesylki, 
    ];

    $ch = curl_init($url);


    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($shipmentData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/vnd.allegro.public.v1+json',
        'Accept: application/vnd.allegro.public.v1+json'
    ));

    $response = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($status == 201) {
        $responseData = json_decode($response, true);

   

        return $responseData;
    } else {
        return "Error: " . $response;
    }
}


function getAllegroCheckoutForm($accessToken, $checkoutFormId) {

    $url = "https://api.allegro.pl/order/checkout-forms/$checkoutFormId";

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.public.v1+json'
    ));

    $response = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($status == 200) {
        $responseData = json_decode($response, true);
        return $responseData;
    } else {
        return "Error: " . $response;
    }
}

function pobierzEtykiete($access_token, $shipping_id, $filename) {
    $label = generateLabel($access_token, [$shipping_id]) ;
    if($label) {
        file_put_contents('/home/users/barii/public_html/finansenl.com.pl/wodki/admin/downloads/etykiety/'.$filename.'.pdf', $label);
        //echo "Protokół wysyłkowy został zapisany.";
    } else {
        //echo "Nie udało się pobrać i zapisać protokołu wysyłkowego.";
    }

}

function getAllegroOrderShipmentsNumber($token, $checkoutFormId) {
    $url = 'https://api.allegro.pl/order/checkout-forms/' . $checkoutFormId . '/shipments';

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json'
    ));

    $response = curl_exec($curl);

    if ($response === false) {
        curl_close($curl);
        return null; 
    }

    curl_close($curl);
    $response_json =  json_decode($response, true);

        $shipmentsArray = $response_json['shipments'];
        foreach ($shipmentsArray as $shipment) {
            $waybill = $shipment['waybill'];
            }
        return $waybill;
}

function checkNewInvoiceName () {
    global $conn;
    $sql = "SELECT numer FROM faktury ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $lastInvoice = $row["numer"];

        $parts = explode('/', str_replace('E', '', $lastInvoice));
        $number = (int) $parts[0];
        $month = (int) $parts[1];
        $year = (int) $parts[2];

        $currentMonth = date("m");
        $currentYear = date("Y");

       if ($month == $currentMonth && $year == $currentYear) {
            $number++;
        } else {
            $number = 1;
            $month = $currentMonth;
            $year = $currentYear;
        }

        return  sprintf("E%02d/%02d/%d", $number, $month, $year);


    } else {

        return sprintf("E01/%s/%s", date("m"), date("Y"));

    }
}

function obliczNettoIVAT($cenaBrutto, $stawkaVAT = 23) {
    $vat = round($cenaBrutto * ($stawkaVAT / (100 + $stawkaVAT)), 2);
    $netto = round($cenaBrutto - $vat, 2);

    return array('netto' => $netto, 'vat' => $vat);
}


function slownie ($kw) {

$t_a = array('','sto','dwieście','trzysta','czterysta','pięćset','sześćset','siedemset','osiemset','dziewięćset');
$t_b = array('','dziesięć','dwadzieścia','trzydzieści','czterdzieści','pięćdziesiąt','sześćdziesiąt','siedemdziesiąt','osiemdziesiąt','dziewięćdziesiąt');
$t_c = array('','jeden','dwa','trzy','cztery','pięć','sześć','siedem','osiem','dziewięć');
$t_d = array('dziesięć','jedenaście','dwanaście','trzynaście','czternaście','piętnaście','szesnaście','siednaście','osiemnaście','dziewiętnaście');

$t_kw_10 = array('kwadryliard','kwadryliardów','kwaryliardy');
$t_kw_9 = array('kwadrylion','kwadrylionów','kwadryliony');
$t_kw_8 = array('tryliard','tryliardów','tryliardy');
$t_kw_7 = array('trylion','trylionów','tryliony');
$t_kw_6 = array('biliard','biliardów','biliardy');
$t_kw_5 = array('bilion','bilionów','bilony');
$t_kw_4 = array('miliard','miliardów','miliardy');
$t_kw_3 = array('milion','milionów','miliony');
$t_kw_2 = array('tysiąc','tysięcy','tysiące');
$t_kw_1 = array('tysiąc','tysięcy','tysiące');
$t_kw_0 = array('złoty','złotych','złote');

  if ($kw!='') {
    $kw=(substr_count($kw,'.')==0) ? $kw.'.00':$kw;
    $tmp=explode(".",$kw);
    $ln=strlen($tmp[0]);
    $tmp_a=($ln%3==0) ? (floor($ln/3)*3):((floor($ln/3)+1)*3);
    for($i = $ln; $i < $tmp_a; $i++) {
      $l_pad .= '0';
      $kw_w = $l_pad . $tmp[0];
    }
    $kw_w=($kw_w=='') ? $tmp[0]:$kw_w;
    $paczki=(strlen($kw_w)/3)-1;
    $p_tmp=$paczki;
    for($i=0;$i<=$paczki;$i++) {
      $t_tmp='t_kw_'.$p_tmp;
      $p_tmp--;
      $p_kw=substr($kw_w,($i*3),3);
      $kw_w_s=($p_kw{1}!=1) ? $t_a[$p_kw{0}].' '.$t_b[$p_kw{1}].' '.$t_c[$p_kw{2}]:$t_a[$p_kw{0}].' '.$t_d[$p_kw{2}];
      if(($p_kw{0}==0)&&($p_kw{2}==1)&&($p_kw{1}<1)) $ka=${$t_tmp}[0]; //możliwe że $p_kw{1}!=1
      else if (($p_kw{2}>1 && $p_kw{2}<5)&&$p_kw{1}!=1) $ka=${$t_tmp}[2];
      else $ka=${$t_tmp}[1];
      $kw_slow.=$kw_w_s.' '.$ka.' ';
    }
  }
  $text = $kw_slow.' '.$tmp[1].'/100 gr.';
  return $text;
}

function generateInvoice($access_token, $checkoutFormId, $post, $numer_faktury = false) {
    // Inicjalizacja sum jako float dla precyzji
    $faktura_suma_netto = 0.0;
    $faktura_suma_vat = 0.0;
    $faktura_suma_brutto = 0.0;

    // Pobieranie danych zamówienia z Allegro
    $zamowienie = getAllegroCheckoutForm($access_token, $checkoutFormId);

    // Aktualizacja nazw produktów na podstawie $post
    $produkty = $post['lineItems'];
    foreach ($produkty as $index => $item) {
        $zamowienie['lineItems'][$index]['offer']['name'] = $item['offer']['name'];
    }
    $products = $zamowienie['lineItems'];

    // Pobieranie danych faktury i nabywcy
    $faktura_dane = $zamowienie['invoice'];
    $faktura_ulica = $post['faktura_ulica'];
    $faktura_city = $post['faktura_miasto'];
    $faktura_zipcode = $post['faktura_zipcode'];
    $faktura_nazwa = $post['faktura_nazwa'];
    $faktura_nip = $post['faktura_nip'];

    // Konwersja kwot na float dla dokładnych obliczeń
    $koszt_dostawy = (float)$zamowienie['delivery']['cost']['amount'];
    $faktura_suma_do_zaplaty = (float)$zamowienie['summary']['totalToPay']['amount'];
    $metoda_wysylki = $zamowienie['delivery']['method']['name'];
    $data_zamowienia_string = $zamowienie['payment']['finishedAt'];
    $date2 = new DateTime($data_zamowienia_string);
    $data_zamowienia = $date2->format('d/m/Y');

    // Obliczanie netto i VAT dla sumy do zapłaty i kosztu dostawy (tylko do wglądu, nie używane w sumie)
    $faktura_suma_wynik = obliczNettoIVAT($faktura_suma_do_zaplaty);
    $koszt_dostawy_wynik = obliczNettoIVAT($koszt_dostawy);

    // Informacje o płatności
    $faktura_id_platnosci = $zamowienie['payment']['id'];
    $faktura_metoda_platnosci_id = $zamowienie['payment']['provider'];
    if ($faktura_metoda_platnosci_id == 'PAYU') {
        $faktura_metoda_platnosci = 'payU';
    } elseif ($faktura_metoda_platnosci_id == 'P24') {
        $faktura_metoda_platnosci = 'przelewy24';
    } else {
        $faktura_metoda_platnosci = 'karta płatnicza';
    }

    // Generowanie lub użycie numeru faktury
    $update = 0;
    if (!$numer_faktury) {
        $numer_faktury = checkNewInvoiceName();
    } else {
        $update = 1;
    }

    // Data wystawienia faktury
    $data_faktury = date("d/m/Y", strtotime(date("Y-m-d")));
    $rand = rand(10000, 1000000);
    $filename = md5($rand) . '.pdf';

    // Inicjalizacja mPDF
    $mpdf = new mPDF('utf-8', 'A4');
    // $mnak usunięto, ponieważ nie było używane

    // Styl CSS
    $css = '
    body{font-family:Arial;font-size:12px;}
    h3.zamowieniedodostawcy {
        text-align: center;
        font-size: 18px;
        padding: 5px 0px;
    }
    h3.zamowieniedodostawcy input{border:0px;text-align:left}
    table.table-list {width:100%;margin-top:10px;}
    table.table-list th{background:#DCDCDC;padding:6px;font-weight:bold;border:2px solid black;border-left:0px;border-right:0px}
    table.table-list tr.zam-list td{font-size:11px;border-bottom:1px solid #333;padding:5px 0px;}
    ';

    // Rozpoczęcie buforowania HTML
    ob_start();
    echo '<form id="szkic_plan">';
    echo '<div style="width:48%;float:left;font-size:11px"><img src="https://www.etykietyweselne.pl/admin/classes/logo_fv.png"> <br />PROLABEL ul. Canaletta 5 , 51-650 Wrocław , Poland<br />
    NIP: 8982095442 ; REGON : 021186818<br />
    Mbank PL 67 1140 2004 0000 3102 6738 8435<br />
    SWIFT : BREXPLPWMBK<br />
    Telefon : +48 508 190 543 ; +48 512-512-661<br />
    E-mail : biuro@prolabel.pl</div>';
    echo '<div style="width:48%;float:right;"><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:center;padding:2px;margin-bottom:5px">Miejsce wystawienia:</h4>';
    echo '<p style="text-align:center;margin:5px">Wrocław</p><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:center;padding:2px;margin-bottom:5px">Data sprzedaży:</h4>';
    echo '<p style="text-align:center;margin:5px">' . $data_zamowienia . '</p><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:center;padding:2px;margin-bottom:5px">Data wystawienia:</h4>';
    echo '<p style="text-align:center;margin:5px">' . $data_faktury . '</p></div><br style="clear:both">';

    echo '<div style="width:48%;float:left;border-top:1px solid black;border-bottom:1px solid black"><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:center;padding:2px">Sprzedawca:</h4>';
    echo '<p>PROLABEL Grzegorz Mączyński<br>ul. Canaletta 5<br>51-650 Wrocław<br>NIP: 898-209-54-42</p></div>';
    echo '<div style="width:48%;float:right;border-top:1px solid black;border-bottom:1px solid black"><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:center;padding:2px">Nabywca:</h4>';
    echo '<p>' . $faktura_nazwa . '<br>' . $faktura_ulica . '<br>' . $faktura_zipcode . ' ' . $faktura_city;
    if (strlen($faktura_nip) > 3) {
        echo '<br>NIP: ' . $faktura_nip;
    }
    echo '</p></div><br style="clear:both;">';

    echo '<h3 class="zamowieniedodostawcy" style="margin:5px 0px 0px 0px">Faktura VAT ' . $numer_faktury . '</h3>';

    // Tabela produktów
    echo '<table cellspacing="0" class="table-list"><tr><th>L.p.</th><th>Kod towaru</th><th>Nazwa towaru</th><th>ilość</th><th>j.m.</th><th>Cena zł</th><th>VAT [%]</th><th>Wartość netto zł</th><th>VAT</th><th>Wartość brutto</th></tr>';
    $i = 0;

    foreach ($products as $product) {
        if (isset($post['lineItems'][$product['id']]['selected'])) {
            $i++;
            $ilosc = $product['quantity'];
            $nazwa = $product['offer']['name'];
            $id_oferty = $product['offer']['id'];
            $cena = (float)$product['price']['amount']; // Cena brutto za jednostkę
            $wynik = obliczNettoIVAT($cena);
            $cena_netto = $wynik['netto'];
            $suma_gross = $cena * $ilosc; // Suma brutto dla pozycji
            $suma_wynik = obliczNettoIVAT($suma_gross);
            $suma_netto = $suma_wynik['netto'];
            $suma_vat = $suma_wynik['vat'];

            // Dodawanie do sum faktury (bez formatowania)
            $faktura_suma_netto += $suma_netto;
            $faktura_suma_vat += $suma_vat;
            $faktura_suma_brutto += $suma_gross;

            echo '<tr class="zam-list">
                <td style="text-align:center">' . $i . '</td>
                <td>' . $id_oferty . '</td>
                <td>' . $nazwa . '</td>
                <td style="text-align:center">' . $ilosc . '</td>
                <td style="text-align:center">szt.</td>
                <td style="text-align:center">' . number_format($cena_netto, 2) . '</td>
                <td style="text-align:center">23%</td>
                <td style="text-align:center">' . number_format($suma_netto, 2) . '</td>
                <td style="text-align:center">' . number_format($suma_vat, 2) . '</td>
                <td style="text-align:center">' . number_format($suma_gross, 2) . '</td>
            </tr>';
        }
    }

    // Dodanie kosztu dostawy
    if ($koszt_dostawy > 0) {
        $i++;
        $koszt_dostawy_wynik = obliczNettoIVAT($koszt_dostawy);
        $koszt_dostawy_netto = $koszt_dostawy_wynik['netto'];
        $koszt_dostawy_vat = $koszt_dostawy_wynik['vat'];

        $faktura_suma_netto += $koszt_dostawy_netto;
        $faktura_suma_vat += $koszt_dostawy_vat;
        $faktura_suma_brutto += $koszt_dostawy;

        echo '<tr class="zam-list">
            <td style="text-align:center">' . $i . '</td>
            <td>-</td>
            <td>WYSYŁKA: ' . $metoda_wysylki . '</td>
            <td style="text-align:center">1</td>
            <td style="text-align:center">szt.</td>
            <td style="text-align:center">' . number_format($koszt_dostawy_netto, 2) . '</td>
            <td style="text-align:center">23%</td>
            <td style="text-align:center">' . number_format($koszt_dostawy_netto, 2) . '</td>
            <td style="text-align:center">' . number_format($koszt_dostawy_vat, 2) . '</td>
            <td style="text-align:center">' . number_format($koszt_dostawy, 2) . '</td>
        </tr>';
    }

    // Podsumowanie tabeli
    echo '<tr><td colspan="7"></td><td style="text-align:center">wartość netto</td><td style="text-align:center">kwota VAT</td><td style="text-align:center">wartość brutto</td></tr>';
    echo '<tr><td colspan="7" style="text-align:right">według stawki VAT 23%</td><td style="text-align:center">' . number_format($faktura_suma_netto, 2) . '</td><td style="text-align:center">' . number_format($faktura_suma_vat, 2) . '</td><td style="text-align:center">' . number_format($faktura_suma_brutto, 2) . '</td></tr>';
    echo '</table>';

    // Sekcja "Razem do zapłaty"
    echo '<div style="width:58%;float:right;margin-top:40px"><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:right;padding:5px;margin-bottom:5px">Razem do zapłaty: ' . number_format($faktura_suma_brutto, 2) . ' zł</h4>';
    echo '<p style="text-align:right;"><strong>Słownie:</strong> ' . slownie($faktura_suma_brutto, 2) . ' złotych</p></div><br style="clear:both">';

    // Informacje o płatności i uwagi
    echo '<p><strong>Zapłacono:</strong> ' . $faktura_id_platnosci . '<br><strong>Typ płatności:</strong> ' . $faktura_metoda_platnosci . '</p>';
    echo '<h4>Uwagi do dokumentu:</h4>';
    echo '<p>' . $post['faktura_uwagi'] . '</p>';
    echo '<div style="border:1px solid #333;height:120px;width:38%;float:left;"><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:center;padding:5px;margin-bottom:5px">Wystawił:</h4><p style="text-align:center">Grzegorz Mączyński</p></div>';
    echo '<div style="border:1px solid #333;height:120px;width:38%;float:right;"><h4 style="margin-top:0px;background:#DCDCDC;border-top:1px solid black;text-align:center;padding:5px;margin-bottom:5px">Odebrał(a):</h4></div><br style="clear:both"><br style="clear:both">';
    echo '</form>';

    // Zakończenie buforowania i generowanie PDF
    $html = ob_get_contents();
    ob_end_clean();

    $mpdf->WriteHTML($css, 1);
    $mpdf->WriteHTML($html, 2);

    // Nazwa pliku w zależności od typu faktury
    if ($update == 1) {
        $filename = strtolower(str_replace('/', '-', $numer_faktury)) . '_korekta.pdf';
    } else {
        $filename = strtolower(str_replace('/', '-', $numer_faktury)) . '.pdf';
    }

    $mpdf->Output('/home/users/barii/public_html/finansenl.com.pl/wodki/admin/downloads/faktury/' . $filename);

    // Zwrócenie danych faktury
    return array(
        'checkout_id' => $checkoutFormId,
        'filename' => $filename,
        'numer_faktury' => $numer_faktury,
        'kwota' => number_format($faktura_suma_brutto, 2)
    );
}

function sendInvoiceToAllegro($token, $checkout_id, $invoiceNumber, $filename) {
    $url = 'https://api.allegro.pl/order/checkout-forms/'.$checkout_id.'/invoices';
    $headers = [
        'Accept: application/vnd.allegro.public.v1+json',
        'Content-Type: application/vnd.allegro.public.v1+json',
        'Authorization: Bearer ' . $token
    ];

    $postData = json_encode([
        'file' => ['name' => $filename],
        'invoiceNumber' => $invoiceNumber
    ]);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Błąd cURL: ' . curl_error($ch);
    }

    curl_close($ch);

    return json_decode($response, true);
}



function uploadInvoiceToAllegro($token, $checkout_id, $invoice_id, $filePath) {

    if (!file_exists($filePath)) {
        return "Plik nie istnieje.";
    }
        $url = 'https://api.allegro.pl/order/checkout-forms/'.$checkout_id.'/invoices/'.$invoice_id.'/file';
$ch = curl_init();


// Ustawienie opcji cURL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/vnd.allegro.public.v1+json',
    'Content-Type: application/pdf',
    'Authorization: Bearer ' . $token // Zastąp {token} odpowiednim tokenem
));

// Przygotowanie do przesłania pliku
$file = fopen($filePath, 'rb');
$fileSize = filesize($filePath);

curl_setopt($ch, CURLOPT_INFILE, $file);
curl_setopt($ch, CURLOPT_INFILESIZE, $fileSize);

// Wykonanie żądania i zamknięcie połączenia
$response = curl_exec($ch);
curl_close($ch);

// Sprawdzenie odpowiedzi
if ($response === false) {
    return 'Błąd cURL: ' . curl_error($ch);
} else {
    return 'Odpowiedź serwera: ' . $response;
}

// Zamknięcie pliku
fclose($file);


}

function getCarrierTrackingInfo($waybill, $token, $carrier_id = 'ALLEGRO') {
    $url = "https://api.allegro.pl/order/carriers/".$carrier_id."/tracking?waybill=".$waybill;

    $headers = [
        "Authorization: Bearer $token",
        "Accept: application/vnd.allegro.public.v1+json"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    if ($response === false) {
        curl_close($ch);
        return null;
    }

    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $result = json_decode($response, true);

if (!empty($result['waybills']) && is_array($result['waybills'])) {
    // Zakładamy, że interesuje nas pierwsza przesyłka w tablicy 'waybills'
    $waybill = $result['waybills'][0];

    if (!empty($waybill['trackingDetails']) && !empty($waybill['trackingDetails']['statuses'])) {
        // Pobierz ostatni status z tablicy 'statuses'
        $statuses = $waybill['trackingDetails']['statuses'];
        $lastStatus = end($statuses);

        // Pobierz kod ostatniego statusu
        $lastStatusCode = $lastStatus['code'];
        return $lastStatusCode;

    } else {
        return false;

    }
} else {
    return false;
}

 
}

function listAllegroThreads($accessToken, $limit = 20, $offset = 0) {
    // Endpoint URL
    $url = 'https://api.allegro.pl/messaging/threads?limit='.$limit.'&offset='.$offset;

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji dla cURL
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.public.v1+json'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    // Wykonanie żądania cURL
    $response = curl_exec($curl);

    // Sprawdzenie czy wystąpiły błędy
    if ($response === false) {
        curl_close($curl);
        return 'CURL Error: ' . curl_error($curl);
    }

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Dekodowanie odpowiedzi JSON do tablicy PHP
    $responseData = json_decode($response, true);

    // Zwrócenie odpowiedzi
    return $responseData;
}

function listAllegroMessages($accessToken, $threadId) {
    // Endpoint URL, zamień {threadId} na rzeczywisty identyfikator wątku
    $url = 'https://api.allegro.pl/messaging/threads/' . $threadId . '/messages';

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji dla cURL
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.public.v1+json'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    // Wykonanie żądania cURL
    $response = curl_exec($curl);

    // Sprawdzenie czy wystąpiły błędy
    if ($response === false) {
        curl_close($curl);
        return 'CURL Error: ' . curl_error($curl);
    }

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Dekodowanie odpowiedzi JSON do tablicy PHP
    $responseData = json_decode($response, true);

    // Zwrócenie odpowiedzi
    return $responseData;
}
function listAllegroMessagesRefresh($id_konta, $threadId) {
    $accessToken = file_get_contents('../../api/demo/accessToken'.$id_konta); 
    // Endpoint URL, zamień {threadId} na rzeczywisty identyfikator wątku
    $url = 'https://api.allegro.pl/messaging/threads/' . $threadId . '/messages';

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji dla cURL
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.public.v1+json'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    // Wykonanie żądania cURL
    $response = curl_exec($curl);

    // Sprawdzenie czy wystąpiły błędy
    if ($response === false) {
        curl_close($curl);
        return 'CURL Error: ' . curl_error($curl);
    }

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Dekodowanie odpowiedzi JSON do tablicy PHP
    $responseData = json_decode($response, true);

    // Zwrócenie odpowiedzi
    return $responseData;
}

function sendAllegroMessage($id_konta, $threadId, $messageContent) {
    $accessToken = file_get_contents('../../api/demo/accessToken'.$id_konta); 
    // Endpoint URL

  

    $url = 'https://api.allegro.pl/messaging/threads/' . $threadId . '/messages';

    // Przygotowanie danych wiadomości
    $postData = json_encode([

            'text' => $messageContent

    ]);

    // Inicjalizacja sesji cURL
    $curl = curl_init($url);

    // Ustawienie opcji dla cURL
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.public.v1+json',
        'Content-Type: application/vnd.allegro.public.v1+json'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);

    // Wykonanie żądania cURL
    $response = curl_exec($curl);

    // Sprawdzenie czy wystąpiły błędy
    if ($response === false) {
        curl_close($curl);
        return 'CURL Error: ' . curl_error($curl);
    }

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Dekodowanie odpowiedzi JSON do tablicy PHP
    $responseData = json_decode($response, true);

    // Zwrócenie odpowiedzi
    return $responseData;
}
function sendAllegroMessageNew($id_konta, $login, $messageContent) {
    $accessToken = file_get_contents('../../api/demo/accessToken'.$id_konta); 
    // Endpoint URL

  

    $url = 'https://api.allegro.pl/messaging/messages';

    // Przygotowanie danych wiadomości
    $postData = json_encode([
        'recipient' => [
            'login' => $login
        ],
        'text' => $messageContent
    ]);

    // Inicjalizacja sesji cURL
    $curl = curl_init($url);

    // Ustawienie opcji dla cURL
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.public.v1+json',
        'Content-Type: application/vnd.allegro.public.v1+json'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);

    // Wykonanie żądania cURL
    $response = curl_exec($curl);

    // Sprawdzenie czy wystąpiły błędy
    if ($response === false) {
        curl_close($curl);
        return 'CURL Error: ' . curl_error($curl);
    }

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Dekodowanie odpowiedzi JSON do tablicy PHP
    $responseData = json_decode($response, true);

    // Zwrócenie odpowiedzi
    return $responseData;
}
function convertDate($originalDate) {
$date = new DateTime($originalDate);

// Formatowanie daty na '22 maja 2024, godz 19:20:14'


// Zastąpienie angielskich nazw miesięcy na polskie
$polishMonths = array(
    'January' => 'stycznia',
    'February' => 'lutego',
    'March' => 'marca',
    'April' => 'kwietnia',
    'May' => 'maja',
    'June' => 'czerwca',
    'July' => 'lipca',
    'August' => 'sierpnia',
    'September' => 'września',
    'October' => 'października',
    'November' => 'listopada',
    'December' => 'grudnia'
);

$today = new DateTime();
$yesterday = new DateTime('-1 day');


if ($date->format('Y-m-d') === $today->format('Y-m-d')) {
    $formattedDate = 'dzisiaj, godz ' . $date->format('H:i:s');
} elseif ($date->format('Y-m-d') === $yesterday->format('Y-m-d')) {
    $formattedDate = 'wczoraj, godz ' . $date->format('H:i:s');
} else {

    $formattedDate = $date->format('d') . ' ' . strftime('%B', $date->getTimestamp()) . ' ' . $date->format('Y, \g\o\d\z H:i:s');
$formattedDate = str_replace(array_keys($polishMonths), array_values($polishMonths), $formattedDate);
}
return $formattedDate;
}





function getCustomerReturns($accessToken, $data_od) {
    // Endpoint URL, zamień {threadId} na rzeczywisty identyfikator wątku
    $url = 'https://api.allegro.pl/order/customer-returns?createdAt.gte='.$data_od;

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji dla cURL
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $accessToken,
        'Accept: application/vnd.allegro.beta.v1+json'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    // Wykonanie żądania cURL
    $response = curl_exec($curl);

    // Sprawdzenie czy wystąpiły błędy
    if ($response === false) {
        curl_close($curl);
        return 'CURL Error: ' . curl_error($curl);
    }

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Dekodowanie odpowiedzi JSON do tablicy PHP
    $responseData = json_decode($response, true);

    // Zwrócenie odpowiedzi
    return $responseData;
}

function getCustomerReturnById($id_konta, $returnId) {
        $accessToken = file_get_contents('../../api/demo/accessToken'.$id_konta); 
    // Endpoint API do pobierania szczegółów zwrotu klienta
    $url = "https://api.allegro.pl/order/customer-returns/" . $returnId;

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji cURL
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $accessToken,
            "Accept: application/vnd.allegro.beta.v1+json"
        ],
    ]);

    // Wykonanie żądania i zapisanie odpowiedzi
    $response = curl_exec($curl);
    $err = curl_error($curl);

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Sprawdzenie, czy wystąpiły błędy podczas żądania
    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
        // Parsowanie JSON na tablicę PHP
        return json_decode($response, true);
    }
}

function initiateRefund($accessToken, $payment_id, $items, $reason = 'REFUND') {
    // Endpoint API do inicjowania zwrotu kosztów
    //Enum: "REFUND" "COMPLAINT" "PRODUCT_NOT_AVAILABLE" "PAID_VALUE_TOO_LOW" "OVERPAID" "CANCELLED_BY_BUYER" "NOT_COLLECTED"
    $url = "https://api.allegro.pl/payments/refunds";

    // Przygotowanie danych zwrotu w formacie JSON
    $postData = json_encode([
        "payment" => [
            "id" => $payment_id
        ],
        "reason" => $reason,
        "lineItems" => $items
    ]);

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji cURL
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $accessToken,
            "Accept: application/vnd.allegro.public.v1+json",
            "Content-Type: application/vnd.allegro.public.v1+json"
        ],
    ]);

    // Wykonanie żądania i zapisanie odpowiedzi
    $response = curl_exec($curl);
    $err = curl_error($curl);

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Sprawdzenie, czy wystąpiły błędy podczas żądania
    if ($err) {

        return "cURL Error #:" . $err;
    } else {
        // Parsowanie JSON na tablicę PHP
        return json_decode($response, true);
    }
}

function createRefundApplication($accessToken, $item_id, $item_quantity) {
    // Endpoint API do tworzenia wniosku o zwrot
    $url = "https://api.allegro.pl/order/refund-claims";

    // Przygotowanie danych zwrotu w formacie JSON
    $postData = json_encode([
        "lineItem" => [
            "id" => $item_id
        ],
        "quantity" => $item_quantity
    ]);

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji cURL
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $accessToken,
            "Accept: application/vnd.allegro.public.v1+json",
            "Content-Type: application/vnd.allegro.public.v1+json"
        ],
    ]);

    // Wykonanie żądania i zapisanie odpowiedzi
    $response = curl_exec($curl);
    $err = curl_error($curl);

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Sprawdzenie, czy wystąpiły błędy podczas żądania
    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
        // Parsowanie JSON na tablicę PHP
        return json_decode($response, true);
    }
}

function getPickupDate($accessToken, $shipmentId, $date='2024-05-28') {
        $url = 'https://api.allegro.pl/shipment-management/pickup-proposals'; // Endpoint for creating a pickup

        $postData = json_encode([
            "shipmentIds" => [
                $shipmentId
        ], 
        "readyDate" => $date

    ]);

    $curl = curl_init();

    // Ustawienie opcji cURL
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $accessToken,
            "Accept: application/vnd.allegro.public.v1+json",
            "Content-Type: application/vnd.allegro.public.v1+json"
        ],
    ]);

    // Wykonanie żądania i zapisanie odpowiedzi
    $response = curl_exec($curl);
    $err = curl_error($curl);

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Sprawdzenie, czy wystąpiły błędy podczas żądania
    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
        // Parsowanie JSON na tablicę PHP
        return json_decode($response, true);
    }
}
function findTodayAt16($array) {
    $today = date("Y-m-d"); // Aktualna data w formacie YYYY-MM-DD
    $timeSlot = "16:00"; // Szukana godzina

    foreach ($array as $item) {
        foreach ($item['proposals'] as $proposal) {
            foreach ($proposal['proposalItems'] as $proposalItem) {
                if (strpos($proposalItem['name'], $today) !== false && strpos($proposalItem['name'], $timeSlot) !== false) {
                    return $proposalItem; // Zwraca pasujący element, gdy znajdzie odpowiednią datę i godzinę
                }
            }
        }
    }

    return null; // Zwraca null, jeśli nie znajdzie pasującego elementu
}
function findLatestTomorrow($array) {
    $tomorrow = date("Y-m-d", strtotime("+1 day")); // Jutrzejsza data w formacie YYYY-MM-DD
    $latestItem = null;
    $latestTime = null;

    foreach ($array as $item) {
        foreach ($item['proposals'] as $proposal) {
            foreach ($proposal['proposalItems'] as $proposalItem) {
                if (strpos($proposalItem['name'], $tomorrow) !== false) {
                    // Wyciągnij czas rozpoczęcia z nazwy
                    $times = explode(' ', $proposalItem['name']);
                    if (isset($times[1])) {
                        $startTime = $times[1];

                        // Porównaj czas, aby znaleźć najpóźniejszy
                        if (is_null($latestTime) || $startTime > $latestTime) {
                            $latestTime = $startTime;
                            $latestItem = $proposalItem;
                        }
                    }
                }
            }
        }
    }

    return $latestItem; // Zwraca element z najpóźniejszym czasem rozpoczęcia jutro lub null, jeśli nie znaleziono
}



function createPickup($accessToken, $shipmentId, $date) {
    $url = 'https://api.allegro.pl/shipment-management/pickups/create-commands'; // Endpoint for creating a pickup

        $postData = json_encode([
        "input" => [
            "shipmentIds" => [
                $shipmentId
            ],
            "pickupDateProposalId" => $date
        ]

    ]);

    $curl = curl_init();

    // Ustawienie opcji cURL
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $accessToken,
            "Accept: application/vnd.allegro.public.v1+json",
            "Content-Type: application/vnd.allegro.public.v1+json"
        ],
    ]);

    // Wykonanie żądania i zapisanie odpowiedzi
    $response = curl_exec($curl);
    $err = curl_error($curl);

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Sprawdzenie, czy wystąpiły błędy podczas żądania
    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
        // Parsowanie JSON na tablicę PHP
        return json_decode($response, true);
    }
}



function getPickupStatus($accessToken, $commandId) {
    // Endpoint API do pobierania szczegółów zwrotu klienta
    $url = "https://api.allegro.pl/shipment-management/pickups/create-commands/" . $commandId;

    // Inicjalizacja sesji cURL
    $curl = curl_init();

    // Ustawienie opcji cURL
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $accessToken,
            "Accept: application/vnd.allegro.public.v1+json",
            "Content-Type: application/vnd.allegro.public.v1+json"
        ],
    ]);

    // Wykonanie żądania i zapisanie odpowiedzi
    $response = curl_exec($curl);
    $err = curl_error($curl);

    // Zamknięcie sesji cURL
    curl_close($curl);

    // Sprawdzenie, czy wystąpiły błędy podczas żądania
    if ($err) {
        echo "cURL Error #:" . $err;
        return null;
    } else {
        // Parsowanie JSON na tablicę PHP
        return json_decode($response, true);
    }
}




?>