<?php
/*
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2016 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/


/**
 * @since 1.6.0
 */
class AdminPaxyprestadownloadlabelController extends ModuleAdminController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function postProcess()
    {
        $idPaxyPoint = $_POST['paxy_order_point_id'];

        $sql2 = new DbQuery();
        $sql2->from('paxy_order_point', 'po');
        $sql2->where('po.id = '.$idPaxyPoint);
        $paxyOrderData = Db::getInstance()->executeS($sql2)[0];

        $apiKey = Configuration::get('paxy_api_key');
        $apiSecret = Configuration::get('paxy_api_secret');
        $ch = curl_init();
        $endpoint = _PAXY_API_URL . '/etykieta/drukuj';
        $params = array(
            'nr_przesylki' => $paxyOrderData['paxy_parcel_number']
        );
        $url = $endpoint . '?' . http_build_query($params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "CL-API-KEY: $apiKey",
            "CL-API-TOKEN: $apiSecret",
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $result = curl_exec($ch);
        header('Cache-Control: public');
        header('Content-type: application/pdf');
        header('Content-Disposition: attachment; filename="'.$paxyOrderData['paxy_parcel_number'].'.pdf"');
        header('Content-Length: '.strlen($result));
        echo $result;
    }


}
