<?php

class ModelExtensionShippingInpostShipping extends Model {
    public function __construct($registry)
    {
        parent::__construct($registry);

        date_default_timezone_set('Europe/Warsaw');

        if (!empty($this->config->get('shipping_inpost_shipping_sandbox_mode'))) {
            $apiKey = $this->config->get('shipping_inpost_shipping_sandbox_api_key');
            $idOrganization = $this->config->get('shipping_inpost_shipping_sandbox_organization_id');
            $geoWidgetKey = $this->config->get('shipping_inpost_shipping_geowidget_sandbox_api_key');
        } else {
            $apiKey = $this->config->get('shipping_inpost_shipping_api_key');
            $idOrganization = $this->config->get('shipping_inpost_shipping_organization_id');
            $geoWidgetKey = $this->config->get('shipping_inpost_shipping_geowidget_api_key');
        }

        $this->load->language('extension/shipping/inpost_shipping');
        $this->load->library('inpostShipping');

        $this->inpostShipping->initialize([
            'sandboxMode' => $this->config->get('shipping_inpost_shipping_sandbox_mode'),
            'apiKey' => $apiKey,
            'idOrganization' => $idOrganization,
            'geoWidgetKey' => $geoWidgetKey,
        ]);
    }

    public function getQuote($address)
    {
        return;
    }

    public function getInpostQuotes($address)
    {
        return $this->inpostShipping
            ->getInpostQuotes($address, $this);
    }

    public function validateShippingMethodSaveRequest($request)
    {
        return $this->inpostShipping
            ->validateShippingMethodSaveRequest($request, $this);
    }

    public function updateShipmentStatus($data)
    {
        $this->inpostShipping
            ->updateShipmentStatus($data, $this);
    }

    public function syncShipmentStatuses()
    {
        $response = $this->inpostShipping
            ->syncShipmentStatuses((int)$this->config->get('shipping_inpost_shipping_sandbox_mode'), $this);

        if (isset($response['error'])) {
            if (!file_exists(DIR_SYSTEM.'../inpost.log')) {
                $f = fopen(DIR_SYSTEM.'../inpost.log', 'w+');
                fclose($f);
            }
            file_put_contents(DIR_SYSTEM.'../inpost.log', date('Y-m-d H:i:s') . ' - ' . json_encode($response) . "\n", FILE_APPEND);
            exit;
        }

        if (empty($response)) {
            exit;
        }

        foreach ($response['items'] as $shipment) {
            $sql = "UPDATE `".DB_PREFIX."inpost_shipping_shipments` SET 
                lastSync = '".strtotime(date('Y-m-d H:i:s'))."',
                status = '".$shipment['status']."',
                tracking_number = '".$shipment['tracking_number']."' 
                WHERE idInpost = '".(int)$shipment['id']."'";
            $this->db->query($sql);
        }
    }
}