Current File : /home/users/barii/public_html/finansenl.com.pl/wodki/admin/classes/the_api2.php
<?php
require_once('../../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 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';

    $shipmentData = [
        "input" => [
            "deliveryMethodId" => getSpecificDeliveryMethodId($token, $shipping_method),
            "sender" => [
                "name" => "Grzegorz Mączyński",
                "company" => "Prolabel",
                "street" => "Mydlana",
                "streetNumber" => "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" => "Główna",
                "streetNumber" => "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"]
                ]
            ],

            "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);

    if (isset($decodedResponse['services'])) {
        foreach ($decodedResponse['services'] as $index => $service) {
            if ($index == $searchId && isset($service['id']['deliveryMethodId'])) {
                return $service['id']['deliveryMethodId'];
            }
        }
    }

    return null; 
}

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 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($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 = $cenaBrutto * ($stawkaVAT / (100 + $stawkaVAT));
    $netto = $cenaBrutto - $vat;

    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) {


$zamowienie = getAllegroCheckoutForm($access_token, $checkoutFormId);

$products = $zamowienie['lineItems'];
$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'];

$koszt_dostawy = $zamowienie['delivery']['cost']['amount'];
$faktura_suma_do_zaplaty = $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('m/d/Y');



$faktura_suma_wynik = obliczNettoIVAT($faktura_suma_do_zaplaty );
$koszt_dostawy_wynik =  obliczNettoIVAT($koszt_dostawy);



$numer_faktury = checkNewInvoiceName();
$data_faktury = date("d/m/Y", strtotime(date("Y-m-d")));

$rand=rand(10000,1000000);
$filename=md5($rand).'.pdf';

$mpdf=new mPDF('utf-8', 'A4');
$mnak=new mPDF('UTF-8',array(50,30),'','' , 0,0,0,0,0,0);



$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;}

';


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';
      echo '</div><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">';
          echo $data_zamowienia;      
      echo '</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">';
         echo $data_faktury;
      echo '</p>';
  echo '</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>';
  echo '</div><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.'<br>NIP: '.$faktura_nip.'</p>';
  echo '</div>';
  
  //echo '<p class="terminrealizacji" style="clear:both">Termin realizacji (dostawy): '.$zamowienie['data'].'</p>';
  echo '<br style="clear:both;"><h3 class="zamowieniedodostawcy" style="margin:5px 0px 0px 0px">Faktura VAT ';
echo $numer_faktury; 
  echo '</h3>';

  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) {
        $i++;
        $ilosc = $product['quantity'];
        $nazwa = $product['offer']['name'];
        $id_oferty = $product['offer']['id'];
        $cena = $product['price']['amount'];
        $wynik = obliczNettoIVAT($cena);

        $cena_netto = number_format($wynik['netto'], 2);
        $suma = number_format($cena * $ilosc, 2);

        $suma_wynik = obliczNettoIVAT($suma);
        $suma_netto = number_format($suma_wynik['netto'],2);
        $suma_vat = number_format($suma_wynik['vat'],2);


        

    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">'.$cena_netto.'</td>
    <td style="text-align:center">23%</td>
    <td style="text-align:center">'.$suma_netto.'</td>
    <td style="text-align:center">'.$suma_vat.'</td>
    <td style="text-align:center">'.$suma.'</td>
    </tr>';

    }
$i++;
if (number_format($koszt_dostawy,0) > 0) {
    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_wynik['netto'],2).'</td>
    <td style="text-align:center">23%</td>
    <td style="text-align:center">'.number_format($koszt_dostawy_wynik['netto'],2).'</td>
    <td style="text-align:center">'.number_format($koszt_dostawy_wynik['vat'],2).'</td>
    <td style="text-align:center">'.number_format($koszt_dostawy,2).'</td>
    </tr>';
    }


  echo '<tr><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td>&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td></tr><tr><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td>&nbsp;</td><td style="text-align:center" colspan="3"><p>według stawki VAT</p></td><td style="text-align:center"><p>wartość netto</p></strong></td><td style="text-align:center"><p>kwota VAT</p></strong></td><td style="text-align:center"><p>Wartość brutto</p></strong></td></tr><tr><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td>&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">&nbsp;</td><td style="text-align:center">23%</td><td style="text-align:center"><p><strong>'.number_format($faktura_suma_wynik['netto'],2).'</p></strong></td><td style="text-align:center"><p><strong>'.number_format($faktura_suma_wynik['vat'],2).'</p></strong></td><td style="text-align:center"><p><strong>'.number_format($faktura_suma_do_zaplaty,2).'</p></strong></td></tr></table>';
  
  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_do_zaplaty,2).' zł</h4>';
      echo '<p style="text-align:right;"><strong>Słownie:</strong> '.slownie($faktura_suma_do_zaplaty,2).' złotych</p></div><br style="clear:both">';
  
  echo '<p><strong>Zapłacono</strong><br><strong>Typ płatności:</strong> przelewy24</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>';






//koniec buforowania planu lekcji
$html=ob_get_contents();
ob_end_clean();

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

$mpdf->Output($filename);


    return array('filename' => $filename, 'numer_faktury' => $numer_faktury);
}

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);








}

$accessToken = file_get_contents('../../api/demo/accessToken0'); 
$refreshToken= file_get_contents('../../api/demo/refreshToken0');
$access_token = $accessToken;

$zamowienie = getAllegroCheckoutForm($access_token, 'dfcb8e80-b4af-11ee-b8fe-f1289181c661');
prettyPrint(getDeliveryServices($access_token));

?>