<?php
/*
 * package modul
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Balikobot_model extends CI_Model
{
    
    public function __construct()
    {
        date_default_timezone_set('Europe/Prague');
        parent::__construct();
    }
    // volani API balikobotu
    private function api_call($auth, $endpoint, $data, $v2 = False){

        $ch = curl_init();
        if($v2) curl_setopt($ch, CURLOPT_URL, "https://api.balikobot.cz/v2/$endpoint");
        else curl_setopt($ch, CURLOPT_URL, "https://api.balikobot.cz/$endpoint");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // pole $aData vstupů
        curl_setopt($ch,CURLOPT_HTTPHEADER, array("Authorization: Basic " . base64_encode($auth),"Content-Type: application/json"));
        $response = curl_exec($ch);
        curl_close($ch);
        
        $aResponse = json_decode($response, true);
        return $aResponse;

    }
    // prehled baliku v Balikobotu
    function overview($auth, $shipping_company){ 
        $result = $this->api_call($auth, "$shipping_company/overview", []);
        return $result;

    }
    // ziskani konkretniho baliku
    function get_package($auth, $shipping_company, $package_id){
        $result = $this->api_call($auth, "$shipping_company/package/".$package_id, []);
        echo pr($result);
        return $result[0];
    }
    // nalzeni baliku v balikobotu dle jejich eshop_id
    function find_package($auth, $shipping_company, $eshop_id){
        $pckgs =  $this->overview($auth, $shipping_company);
        foreach ($pckgs as $key => $value) {
            if($value["eshop_id"] == $eshop_id){
                return $value;
            }
        }
        return $pckgs;
    }

    // pridani baliku do balikobotu s danymi daty
    function add_package($auth, $shipping_company, $data){
        $result = $this->api_call($auth, "$shipping_company/add", $data);
        return $result[0];
    }
    // ziskani sledovani baliku
    function get_tracking($auth, $shipping_company, $carrier_id){
        $result = $this->api_call($auth, "$shipping_company/track", [["id" => $carrier_id]], True);
        return $result[0];
    }



}